Note that there are some explanatory texts on larger screens.

plurals
  1. POTwo-way bind a combobox to a simple string array
    text
    copied!<p>I have a simple class that provides state codes like this:</p> <pre><code>public class StateProvider { static string[] _codes = new string[] { "AL", "AK", ... }; public string[] GetAll() { return _codes; } } </code></pre> <p>My model class that supports the view looks a little like this:</p> <pre><code>public class ProjectModel : ChangeNotifier { StateProvider _states = new StateProvider(); public ProjectModel() { Project = LoadProject(); } ProjectEntity _project; public ProjectEntity Project { get { return _project; } set { _project = value; FirePropertyChanged("Project"); } } public string[] States { get { return _states.GetAll(); } } } </code></pre> <p>And my ComboBox XAML looks like this:</p> <pre><code>&lt;ComboBox SelectedValue="{Binding Project.State, Mode=TwoWay}" SelectedValuePath="{Binding RelativeSource={RelativeSource Self}}" ItemsSource="{Binding States}" /&gt; </code></pre> <p>The binding works from the UI to the entity - if I select the state from the combo then the value gets pushed to the project entity and I can save it. However, if I shutdown and reload, the state code value doesn't bind from the entity to the UI and the combo shows nothing selected. Then, of course, a subsequent save nulls the entity's state value.</p> <p>I want this very simple since I want to display state codes and save state codes (I don't want to display the full state name). So I don't want to have to muck with creating a State class that has Code and FullName properties and avoid having to use the SelectedValuePath and DisplayMemberPath properties of the combobox.</p> <p>Edit: Added to the code how ProjectModel does change notification. Note that the ProjectEntity class does this too. Trust me, it works. I've left it out because it also inherits from an Entity base class that does change notification through reflection. TwoWay binding works on everything but for the combobox.</p>
 

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