I am trying to learn the MVVM pattern in WPF and I am running into some issues with bindings and collections. I don’t like binding to the index of the collection because the collection changes.
I have MyModelClass : ObservableCollection<MyData>
The MyData class has a property called DataValue in it to hold my custom information. I fill the MyModelClass with MyData objects. In the view model class (MyViewModel) I have a property CurrentData of type MyModelClass.
Now in this case, my binding is to a combo box.
Here is what the binding looks like:
<ComboBox Name="cmbxData"
ItemsSource="{Binding Path=CurrentData}"
DisplayMemberPath="DataValue"
SelectedValuePath="DataValue"
SelectedValue="{Binding Path=CurrentData[0].DataValue}"/>
This all works fine and the MyViewModel class has the interface setup for PropertyChanged notifications.
I need to refresh the information this holds every few seconds.
I am refreshing the collection by doing something like this inside the MyModelClass:
public Class MyModelClass : ObservableCollection<MyData>
{
private static MyModelClass current = null;
public static MyModelClass Current
{
get
{
if(current == null)
current = new MyModelClass();
return current;
}
}
private void UpdateModel(MyData newData)
{
MyModelClass newModel = new MyModelClass();
newModel.Add(newData);
current = newModel;
}
}
Inside MyViewModel there is this:
MyModelClass CurrentData = MyModelClass.Current;
I tried my best to give as much code as I could and keep it simple. Please let me know if there is more needed to clarify. Thank you for any suggestions on how to fix my issue.
In case you missed it:
Problem: How can I bind to the collection, or the value I want to display in the collection, without using the index like I have shown above (SelectedValue="{Binding Path=CurrentData[0].DataValue}")? How can I fix this or change my implementation to be correct?
Thanks,
Add a property on MyModelClass called “SelectedData” or something similiar.
Then bind that property to the SelectedItem property of ComboBox