Problem with Silverlight ComboBoxItem binding - silverlight

I just can't make the following situation work:
I have a class, with the following implementation:
public class SelectionItem<T> : ViewModelBase where T : Entity
{
private bool? _isSelected;
public bool? IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
RaisePropertyChanged("IsSelected");
}
}
public T Item { get; set; }
}
And I have the following property on my ViewModel:
private IEnumerable<SelectionItem<DB_Aux_Pessoas>> _vendedores;
public IEnumerable<SelectionItem<DB_Aux_Pessoas>> Vendedores
{
get
{
return _vendedores;
}
set
{
_vendedores = value;
RaisePropertyChanged("Vendedores");
}
}
Then, in my View, I have the ComboBox:
<ComboBox Margin="3,0,0,0"
Height="23"
Width="200"
ItemsSource="{Binding Vendedores, Mode=TwoWay}"
Grid.Column="1"
Grid.Row="1"
HorizontalAlignment="Left">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" />
<TextBlock Text="{Binding Item.NomeRazaoSocial}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
But when I change the CheckBox on the ComboBoxItem, it does not reflect on the property.
The code for DB_Aux_Pessoas is below:
[MetadataTypeAttribute(typeof(DB_Aux_Pessoas.DB_Aux_PessoasMetadata))]
public partial class DB_Aux_Pessoas
{
// This class allows you to attach custom attributes to properties
// of the DB_Aux_Pessoas class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class DB_Aux_PessoasMetadata
{
// Metadata classes are not meant to be instantiated.
private DB_Aux_PessoasMetadata()
{
}
public Nullable<short> Cliente { get; set; }
public string Id_Numero { get; set; }
public string NomeRazaoSocial { get; set; }
public Nullable<short> Supervisor { get; set; }
public Nullable<short> Vendedor { get; set; }
}
}
What I am doing wrong here?
Tks in advance.

I can't check this right now, but I'm fairly sure the dependency property IsChecked will only accept a binding to a bool and NOT a Nullable<bool>. You might have to do the conversion in your viewmodel and decide which should be the appropriate default for a null value.

This works fine for me. Add an extra property to give you some visual feedback like this:
public class SelectionItem<T> : ViewModelBase
{
private bool? _isSelected;
public bool? IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
RaisePropertyChanged("IsSelected");
RaisePropertyChanged("Feedback");
}
}
public string Feedback
{
get
{
if (!this.IsSelected.HasValue)
{
return "null";
}
if (this.IsSelected.Value)
{
return "yes";
}
return "no";
}
}
public T Item { get; set; }
}
And in your xaml, add an extra TextBlock to show the result:
<ComboBox Grid.Column="1"
Grid.Row="1"
Height="23"
Margin="3,0,0,0"
Width="200"
HorizontalAlignment="Left"
ItemsSource="{Binding Vendedores, Mode=TwoWay}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" />
<TextBlock Text="{Binding Item.NomeRazaoSocial}" />
<TextBlock Text="{Binding Feedback}" Margin="5,0,0,0" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
If you see "Yes", "No", "Null" changing as you click the checkboxes, then it's working. Your code worked for me.

public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.RegisterAttached("IsChecked", typeof(bool), typeof(...),
new PropertyMetadata(false, delegate(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
...
}
IsChecked is bool. You can possibly track BindingExpression Error in Output window.

Related

Why twoway binding doen't work as expected?

I need some help with binding. Twoway mode doesn't work at all.
I fill my window with data passed to the constructor and it's working fine.
The problem is that I can't rewrite some data imputed in the window control even if I use Twoway binding.
Below is how I open window
var tempInregistrare = BaseConnection.GetInregistrareById(itemSelected.InregistrareId.ToString());
var tichet = new TichetView(new InregistrareModel {
Id =tempInregistrare.Id,
NumeFurnizor = tempInregistrare.NumeFurnizor,
IdFurnizor = tempInregistrare.IdFurnizor,
NumeProdus = tempInregistrare.NumeProdus......
ticket.Show();
Here is window constructor with DataContext set to self.
public TichetView(InregistrareModel inregistrare)
{
InitializeComponent();
InregistrareModel = inregistrare;
DataContext = this;
grdButtonsPrint.Visibility = Visibility.Visible;
}
public InregistrareModel InregistrareModel
{
get => inregistrareModel;
set
{
if (value != inregistrareModel)
{
inregistrareModel = value;
NotifyPropertyChanged();
}
}
}
public class InregistrareModel
{
public int Id { get; set; }
public int IdProdus { get; set; }
public int IdFurnizor { get; set; }
public string NumeProdus { get; set; }
public string NumeFurnizor { get; set; }
public string NrAuto { get; set; }
public string NumeSofer { get; set; }
public double CantitateInitiala { get; set; }
public double CantitateIesire { get; set; }
public double Umiditate { get; set; }
public double CantitateScazuta { get; set; }
public double CantitateMarfa { get; set; }
public DateTime DataIntrare { get; set; }
public DateTime DataIesire { get; set; }
public FurnizorModel Furnizor { get; set; }
public int NIR { get; set; }
}
And here is Xaml of window
<TextBlock Grid.Row="2" Grid.Column="2" VerticalAlignment="Center">Intrare</TextBlock>
<TextBox Grid.Row="2" Grid.Column="3" Text="{Binding InregistrareModel.CantitateInitiala}"/>
<TextBlock Grid.Row="4" Grid.Column="2" VerticalAlignment="Center">Umiditatea (%)</TextBlock>
<TextBox x:Name="txtUmiditate" Grid.Row="4" Grid.Column="3" IsReadOnly="False" Text="{Binding InregistrareModel.Umiditate, Mode=TwoWay}"/>
<TextBlock Grid.Row="5" Grid.Column="2" VerticalAlignment="Center">Cantitatea scazuta</TextBlock>
<TextBox x:Name="txtCantitateScazuta" Grid.Row="5" Grid.Column="3" IsReadOnly="False" Text="{Binding InregistrareModel.CantitateScazuta, Mode=TwoWay}"/>
<TextBlock Grid.Row="6" Grid.Column="2" VerticalAlignment="Center">Iesire</TextBlock>
<TextBox Grid.Row="6" Grid.Column="3" Text="{Binding InregistrareModel.CantitateIesire}"/>
<TextBlock Grid.Row="7" Grid.Column="2" VerticalAlignment="Center">Dată iesire</TextBlock>
<TextBox Grid.Row="7" Grid.Column="3" Text="{Binding InregistrareModel.DataIesire,StringFormat='{}{0:HH:HH dd/M/yyyy}'}"/>
<TextBlock Grid.Row="10" Grid.Column="2" VerticalAlignment="Center">Net</TextBlock>
<TextBox Grid.Row="10" Grid.Column="3" Text="{Binding InregistrareModel.CantitateMarfa}"/>
All text boxes are filled with data expect the second and third that I fill by hand.
The goal that I can't achieve right now is to take data from 1st textbox(InregistrareModel.CantitateInitiala) to type in 3rd(txtCantitateScazuta) some data and show the result in the last textbox so after I update my database with this data.
I totally agree with #Peter Boone.
You have a lot of gross architectural mistakes in the Solution and for good reason it needs to be completely redone.
But if you do not have such an opportunity, try to implement this option.
For fields (TextBox, TextBlock) that change, declare properties in the Window.
In the body of these properties, implement communication with the parent container (InregistrareModel) and with other properties.
Let's say you have a CantitateInitiala property that affects the value of the CantitateScazuta property.
public InregistrareModel InregistrareModel
{
get => inregistrareModel;
set
{
if (value != inregistrareModel)
{
inregistrareModel = value;
NotifyPropertyChanged();
CantitateInitiala = InregistrareModel.CantitateInitiala;
}
}
public double CantitateInitiala
{
get => InregistrareModel.CantitateInitiala;
set
{
if (value != InregistrareModel.CantitateInitiala)
{
InregistrareModel.CantitateInitiala = value;
NotifyPropertyChanged();
// Calculation of the CantitateScazuta value
double cantSc = CantitateInitiala / 123.45;
CantitateScazuta = cantSc;
}
}
}
public double CantitateScazuta
{
get => InregistrareModel.CantitateScazuta;
set
{
if (value != InregistrareModel.CantitateScazuta)
{
InregistrareModel.CantitateScazuta = value;
NotifyPropertyChanged();
}
}
}
In XAML, change the bindings for these fields:
<TextBlock Grid.Row="2" Grid.Column="2" VerticalAlignment="Center">Intrare</TextBlock>
<TextBox Grid.Row="2" Grid.Column="3" Text="{Binding CantitateInitiala}"/>
<TextBlock Grid.Row="4" Grid.Column="2" VerticalAlignment="Center">Umiditatea (%)</TextBlock>
<TextBox x:Name="txtUmiditate" Grid.Row="4" Grid.Column="3" IsReadOnly="False" Text="{Binding InregistrareModel.Umiditate, Mode=TwoWay}"/>
<TextBlock Grid.Row="5" Grid.Column="2" VerticalAlignment="Center">Cantitatea scazuta</TextBlock>
<TextBox x:Name="txtCantitateScazuta" Grid.Row="5" Grid.Column="3" IsReadOnly="False" Text="{Binding CantitateScazuta, Mode=TwoWay}"/>
Но нужно тщательно продумать алгоритм зависимостей свойств в том случае, если они имеют циклическую зависимость.
То есть не только изменение CantitateInitiala влияет на значение CantitateScazuta, но также существует обратная зависимость CantitateInitiala от изменения CantitateScazuta.
You should make the ViewModel a separate file/class. Let's call it TichetViewModel. This class should have the InregistrareModel. Something like this:
public class TichetViewModel : ObservableObject
{
private InregistrareModel _InregistrareModel;
public InregistrareModel InregistrareModel
{
get { return _InregistrareModel; }
set
{
if (value != _InregistrareModel)
{
_InregistrareModel = value;
NotifyPropertyChanged();
}
}
}
public TichetViewModel()
{
InregistrareModel = new InregistrareModel();
}
}
Then set the DataContext of TichetView in either you code behind or in xaml.
Code behind:
TichetView.xaml.cs
public TichetView()
{
InitializeComponent();
DataContext = new TichetViewModel();
}
or in xaml
TichetView.xaml
<Window.DataContext>
<local:TichetViewModel />
</Window.DataContext>
I like doing this in xaml because the Intellisense in Visual Studio picks this up and autocompletes based on the classes.
Implement INotifyPropertyChanged on the properties of the InregistrareModel. Like this:
public class InregistrareModel : ObservableObject
{
private int _Id;
public int Id
{
get { return _Id; }
set
{
if (value != _Id)
{
_Id = value;
NotifyPropertyChanged();
}
}
}
private string _NumeProdus;
public string NumeProdus
{
get { return _NumeProdus; }
set
{
if (value != _NumeProdus)
{
_NumeProdus = value;
NotifyPropertyChanged();
}
}
}
}

ListBox DataTemplate for dynamically loaded type

I have a sample MVVM WPF application and I'm having problems creating DataTemplates for my dynamically loaded model. Let me try explain:
I have the following simplified classes as part of my Model, which I'm loading dynamically
public class Relationship
{
public string Category { get; set; }
public ParticipantsType Participants { get; set; }
}
public class ParticipantsType
{
public ObservableCollection<ParticipantType> Participant { get; set; }
}
public class ParticipantType
{
}
public class EmployeeParticipant : ParticipantType
{
public EmployeeIdentityType Employee { get; set; }
}
public class DepartmentParticipant : ParticipantType
{
public DepartmentIdentityType Department { get; set; }
}
public class EmployeeIdentityType
{
public string ID { get; set; }
}
public class DepartmentIdentityType
{
public string ID { get; set; }
}
Here is how my View Model looks like. I created a generic object Model property to expose my Model:
public class MainViewModel : ViewModelBase<MainViewModel>
{
public MainViewModel()
{
SetMockModel();
}
private void SetMockModel()
{
Relationship rel = new Relationship();
rel.Category = "213";
EmployeeParticipant emp = new EmployeeParticipant();
emp.Employee = new EmployeeIdentityType();
emp.Employee.ID = "222";
DepartmentParticipant dep = new DepartmentParticipant();
dep.Department = new DepartmentIdentityType();
dep.Department.ID = "444";
rel.Participants = new ParticipantsType() { Participant = new ObservableCollection<ParticipantType>() };
rel.Participants.Participant.Add(emp);
rel.Participants.Participant.Add(dep);
Model = rel;
}
private object _Model;
public object Model
{
get { return _Model; }
set
{
_Model = value;
NotifyPropertyChanged(m => m.Model);
}
}
}
Then I tried creating a ListBox to display specifically the Participants Collection:
<ListBox ItemsSource="{Binding Path=Model.Participants.Participant}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Expander Header="IdentityFields">
<!-- WHAT TO PUT HERE IF PARTICIPANTS HAVE DIFFERENT PROPERTY NAMES -->
</Expander>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
The problem is:
I don't know how to create a template that can handle both type of ParticipantTypes, in this case I could have EmployeeParticipant or DepartmentParticipant so depending on that, the data binding Path would be set to Employee or Department properties accordingly
I though about creating a DataTemplate for each type (e.g. x:Type EmployeeParticipant) but the problem is that my classes in my model are loaded dynamically at runtime so VisualStudio will complain that those types don't exist in the current solution.
How could I represent this data in a ListBox then if my concrete types are not known at compile time, but only at runtime?
EDIT: Added my test ViewModel class
You can still create a DataTemplate for each type but instead of using DataType declarations to have them automatically resolve you can create a DataTemplateSelector with a property for each template (assigned from StaticResource in XAML) that can cast the incoming data item to the base class and check properties or otherwise determine which template to use at runtime. Assign that selector to ListBox.ItemTemplateSelector and you'll get similar behavior to what DataType would give you.
That's not a good view-model. Your view-model should be view-centric, not business-centric. So make a class that can handle all four cases from a visual perspective, then bridge your business classes over to that view-model.
EDIT:
Working off your code:
<ListBox ItemsSource="{Binding Path=Model.Participants}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Expander Header="IdentityFields">
<TextBlock Text={Binding Id} />
<TextBlock Text={Binding Name} />
</Expander>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I changed the binding, I assume that was a mistake?
I would create a ViewModel for Participant:
public class Participant_VM : ViewModelBase
{
private string _name = string.Empty;
public string Name
{
get
{
return _name ;
}
set
{
if (_name == value)
{
return;
}
_name = value;
RaisePropertyChanged(() => Name);
}
private string _id= string.Empty;
public string Id
{
get
{
return _id;
}
set
{
if (_id== value)
{
return;
}
_id = value;
RaisePropertyChanged(() => Id);
}
}
}
Modify the ListBox as follows.
<ListBox ItemsSource="{Binding Model.Participants.Participant}">
<ListBox.Resources>
<DataTemplate DataType="{x:Type loc:DepartmentParticipant}">
<Grid>
<TextBlock Text="{Binding Department.ID}"/>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type loc:EmployeeParticipant}">
<Grid>
<TextBlock Text="{Binding Employee.ID}"/>
</Grid>
</DataTemplate>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Expander Header="IdentityFields">
<!-- WHAT TO PUT HERE IF PARTICIPANTS HAVE DIFFERENT PROPERTY NAMES -->
<ContentPresenter Content="{Binding }"/>
</Expander>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Edit:
loc refers to the namespace in which the DepartmentParticipant and EmployeeParticipant are present. Hope you are familiar with adding namespaces.

DataGrid won't update ViewModel

I've got a datagrid which is bound to an ObservableCollection of the ViewModel below. The Datagrid will display all values correctly, so the binding seems to be working, but if I change some value the Grid won't call the setter's of my VM. Could somebody tell me why?
Here's my ViewModel:
public class DocumentVm : ViewModelBase
{
private Document document;
public bool IsNew { get; private set; }
public Document Document {
get { return document; }
}
public DocumentVm(Document document)
{
this.document = document;
IsNew = false;
}
public DocumentVm(Document document, bool isNew)
{
this.document = document;
IsNew = isNew;
}
public String Name
{
get { return document.Name; }
set { document.Name = value; RaisePropertyChangedEvent("Name");}
}
public String Path
{
get { return document.Path; }
set { document.Path = value; }
}
public String Metadata
{
get { return document.Metadata; }
set { document.Metadata = value; }
}
public int SpeechId
{
get { return document.SpeechId; }
set { document.SpeechId = value; }
}
}
Here is the XAML Code:
<DataGrid Margin="3" Grid.Row="7" Grid.Column="1" BorderThickness="0"
ItemsSource="{Binding Path=CurrentSpeech.Documents, Mode=TwoWay}"
SelectedItem="{Binding Path=CurrentSpeech.CurrentDocument, Mode=TwoWay}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Name" Width="SizeToCells">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Name, Mode=TwoWay}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="MetaDaten" Width="SizeToCells">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Metadata, Mode=TwoWay}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Pfad" Width="SizeToCells">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
Thank you all!
UpdateSourceTrigger=PropertyChanged on the Bindings was missing.
Not sure why the setters aren't getting called but if you use dependency properties they actually do get called. I'm far too drunk to investigate why the CLR properties aren't getting set in your project but this works for me.
public partial class MainWindow : Window
{ public ObservableCollection<DocumentVm> Items
{
get { return (ObservableCollection<DocumentVm>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register("Items", typeof(ObservableCollection<DocumentVm>), typeof(MainWindow), new PropertyMetadata(null));
public MainWindow()
{
InitializeComponent();
Items = new ObservableCollection<DocumentVm>();
Items.Add(new DocumentVm() { Name = "Name 1"});
Items.Add(new DocumentVm() { Name = "Name 2"});
}
}
public class DocumentVm : DependencyObject
{
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name", typeof(string), typeof(DocumentVm), new PropertyMetadata(null, new PropertyChangedCallback( (s, e)=>
{
// This will run when the property is set.
})));
}

Binding SetectedItem in ComboBox WPF

I have a UserControl with ComboBox.
<ComboBox Grid.Row="8" Grid.Column="1"
VerticalAlignment="Center"
x:Name="cmbCategory"
ItemsSource="{Binding ElementName=ucAppiGeneralInfo, Path=Categories, Mode=TwoWay}"
SelectedItem="{Binding ElementName=ucAppiGeneralInfo, Path=SelectedCategory, Mode=TwoWay}"
IsEditable="True"
IsSynchronizedWithCurrentItem="True"
SelectedValuePath="CAT_ID"
TextSearch.TextPath="CAT_NAME">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=CAT_NAME}"/>
<TextBlock Text=" - "/>
<TextBlock Text="{Binding Path=PUBLIC_DESCRIPTION}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
The code behind is:
public partial class AppiGeneralInfoUC : UserControl
{
public DataTable Categories
{
get { return (DataTable)GetValue(CategoriesProperty); }
set { SetValue(CategoriesProperty, value);}
}
public static readonly DependencyProperty CategoriesProperty =
DependencyProperty.Register(
"Categories",
typeof(DataTable),
typeof(AppiGeneralInfoUC),
new UIPropertyMetadata(null));
public String SelectedCategory
{
get { return (String)GetValue(SelectedCategoryProperty); }
set
{
SetValue(SelectedCategoryProperty, value);
}
}
public static readonly DependencyProperty SelectedCategoryProperty =
DependencyProperty.Register(
"SelectedCategory",
typeof(String),
typeof(AppiGeneralInfoUC),
new UIPropertyMetadata(null));
public AppiGeneralInfoUC()
{
InitializeComponent();
}
}
I have a window which use the UserControl:
<TabControl>
<TabItem Header="Information">
<my:AppiGeneralInfoUC x:Name="ucAppiGeneralInfo"
Categories="{Binding Path=Categories, Mode=TwoWay}"
SelectedCategory="{Binding Path=SelectedCategory, Mode=TwoWay}" />
</TabItem>
the code behind is:
public partial class ApplicationWindow : Window
{
VMBase appiGeneralInfoWin = new AppiGeneralInfoVM();
public ApplicationWindow()
{
InitializeComponent();
ucAppiGeneralInfo.DataContext = appiGeneralInfoWin;
}
public void updateAction(string cat_id)
{
this.Title = "Update application";
(appiGeneralInfoWin as AppiGeneralInfoVM).setSelectedCategory(cat_id);
} ...
And finally I have ViewModel class:
class AppiGeneralInfoVM : VMBase
{
private DataTable categories = null;
private String selectedCategory = null;
public DataTable Categories
{
get { return this.categories; }
set
{
this.categories = value;
this.OnPropertyChanged("Categories");
}
}
public String SelectedCategory
{
get { return this.selectedCategory; }
set
{
this.selectedCategory = value;
this.OnPropertyChanged("SelectedCategory");
}
}
public AppiGeneralInfoVM()
{
ServicesLoader.LoadRunTimeServices();
Categories = GetService<CategoryBLL>().getCategories();
}
public void setSelectedCategory(string cat_id)
{
SelectedCategory = Categories.Select("cat_id =" + "'"+cat_id+"'")[0]["CAT_NAME"].ToString();
}
Everything works well but i have problem with the selectedItem (SelectedCategory),
it's not update at all....
I think it happens because your SelectedItem has string type while your collection is DataTable (which enumerates DataRow). Try changing your collection to be IEnumerable<string>

How can I bind an ObservableCollection to TextBoxes in a DataTemplate?

I am trying to successfully TwoWay bind an ObservableCollection to TextBoxes in a DataTemplate. I can get the data to display properly, but I am unable to change the list data through the UI. I have a Model class named 'model' which contains an ObservableCollection named 'List'. The class implements the INotifyPropertyChanged interface. Here is the xaml for the shell. The DataContext for Window1's grid is set to "theGrid.DataContext=model"
<Window x:Class="BindThat.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BindThat"
Title="Window1" Height="300" Width="300">
<StackPanel x:Name="theGrid">
<GroupBox BorderBrush="LightGreen">
<GroupBox.Header>
<TextBlock Text="Group" />
</GroupBox.Header>
<ItemsControl ItemsSource="{Binding Path=List}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</GroupBox>
</StackPanel>
This is the code for the Model class:
class Model : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
private ObservableCollection<string> _list = new ObservableCollection<string>();
public ObservableCollection<string> List
{
get { return _list; }
set
{
_list = value;
NotifyPropertyChanged("List");
}
}
public Model()
{
List.Add("why");
List.Add("not");
List.Add("these?");
}
}
Could anyone advise if I am going about this the correct way?
You need a property to bind two way, so string is not good for this.
Wrap it in a string object, like this:
public class Model
{
public ObservableCollection<StringObject> List { get; private set; }
public Model()
{
List = new ObservableCollection<StringObject>
{
new StringObject {Value = "why"},
new StringObject {Value = "not"},
new StringObject {Value = "these"},
};
}
}
public class StringObject
{
public string Value { get; set; }
}
and bind to Value property instead of "."
Also, you don't need to notify of a change in observable collection, so until your model has some other propertis of its own, it does not need to have INotifyPropertyChange. If you want your ItemsControl react to changes in the individual StringObjects, then you should add INotifyPropertyChanged to a StringObject.
And yet again, two way binding is default, so you need only
<TextBox Text="{Binding Path=Value}" />
in your binding.
I believe you need to derive your collection items from DependencyObject for TwoWay binding to work. Something like:
public class DependencyString: DependencyObject {
public string Value {
get { return (string)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(string), typeof(DependencyString), new UIPropertyMetadata(""));
public override string ToString() {
return Value;
}
public DependencyString(string s) {
this.Value = s;
}
}
public class Model {
private ObservableCollection<DependencyString> _list = new ObservableCollection<DependencyString>();
public ObservableCollection<DependencyString> List {
get { return _list; }
}
public Model() {
List.Add(new DependencyString("why"));
List.Add(new DependencyString("not"));
List.Add(new DependencyString("these?"));
}
}
...
<StackPanel x:Name="theGrid">
<GroupBox BorderBrush="LightGreen">
<GroupBox.Header>
<TextBlock Text="Group" />
</GroupBox.Header>
<ItemsControl ItemsSource="{Binding Path=List}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Value, Mode=TwoWay}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</GroupBox>
</StackPanel>
xaml view:
<ItemsControl ItemsSource="{Binding List}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
in code behind in the constructor:
DataContext = new ViewModel();
in ViewModel Class:
class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private ObservableCollection<StringObject> _List = new ObservableCollection<StringObject>();
public ObservableCollection<StringObject> List
{
get { return _List; }
set
{
_List = value;
NotifyPropertyChanged("List");
}
}
public ViewModel()
{
List = new ObservableCollection<StringObject>
{
new StringObject {Value = "why"},
new StringObject {Value = "not"},
new StringObject {Value = "these"}
};
}
}
public class StringObject
{
public string Value { get; set; }
}
Be careful with a collection with type string it doesn't work, you have to use an object => StringObject

Resources