Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to bind to a collection without using an index of the collection?
    primarykey
    data
    text
    <p>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.</p> <p>I have <code>MyModelClass : ObservableCollection&lt;MyData&gt;</code></p> <p>The <code>MyData</code> class has a property called <code>DataValue</code> in it to hold my custom information. I fill the <code>MyModelClass</code> with <code>MyData</code> objects. In the view model class (<code>MyViewModel</code>) I have a property <code>CurrentData</code> of type <code>MyModelClass</code>. </p> <p>Now in this case, my binding is to a combo box. Here is what the binding looks like:</p> <pre><code>&lt;ComboBox Name="cmbxData" ItemsSource="{Binding Path=CurrentData}" DisplayMemberPath="DataValue" SelectedValuePath="DataValue" SelectedValue="{Binding Path=CurrentData[0].DataValue}"/&gt; </code></pre> <p>This all works fine and the <code>MyViewModel</code> class has the interface setup for PropertyChanged notifications. I need to refresh the information this holds every few seconds. </p> <p>I am refreshing the collection by doing something like this inside the <code>MyModelClass</code>:</p> <pre><code>public Class MyModelClass : ObservableCollection&lt;MyData&gt; { 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; } } </code></pre> <p>Inside <code>MyViewModel</code> there is this:</p> <pre><code>MyModelClass CurrentData = MyModelClass.Current; </code></pre> <p>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. </p> <p>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 (<code>SelectedValue="{Binding Path=CurrentData[0].DataValue}"</code>)? How can I fix this or change my implementation to be correct?</p> <p>Thanks,</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload