Reputation: 693
I am trying to populate the wpf combobox with list. I have two problems with it.
Here is my XAML for the combobox:
<Label Target="{Binding ElementName=State}" Grid.Row="10" Grid.Column="0">State:</Label>
<ComboBox x:Name="State" Margin="10,0,0,10" Grid.Column="1" Grid.Row="10" ItemsSource="{Binding Path=States, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" Validation.Error="Validation_Error" SelectedValue="{Binding Path=FamilyMember.State}"/>
<TextBlock Grid.Column="2" Grid.Row="10" Style="{StaticResource TextBlockStyle}" Text="{Binding (Validation.Errors)[0].ErrorContent, ElementName=State}" Margin="10,0,0,10"/>
Here is my partial viewmodel where I am declaring and populating my States object.
Property in ViewModel
public ObservableCollection<string> States;
Constructor:
States = new ObservableCollection<string>();
States.Add("One");
States.Add("Two");
States.Add("Three");
States.Add("Four");
States.Add("Five");
Here is the proof from my Debug that I am getting states correctly to a view.
And another problem is that my data annotation error is not working
Here is my partial Model:
It is working for other fields without any problems as seen below:
Upvotes: 1
Views: 7876
Reputation: 89
Change the States as full property in your view model and add the display member path in your combo box for your xaml file.
View Model:
public ObservableCollection<string> _state = new ObservableCollection<string>();
public ObservableCollection<string> States
{
get{return _state;}
set {_state = value; OnPropertyChange("States");}
}
If you need more clarification refer this page: https://www.codeproject.com/Articles/301678/Step-by-Step-WPF-Data-Binding-with-Comboboxes
Upvotes: -1
Reputation: 27039
Change this field:
public ObservableCollection<string> States;
to a property:
public ObservableCollection<string> States {get; set;}
Binding does not work on fields even if they are public.
Upvotes: 9