Andy Johnson
Andy Johnson

Reputation: 693

WPF ComboBox Binding to List<string>

I am trying to populate the wpf combobox with list. I have two problems with it.

  1. It doesn't populate anything
  2. I am using Data Annotation for the validation. It doesn't set "Required" Error message in error display area.

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. enter image description here

And another problem is that my data annotation error is not working Here is my partial Model: enter image description here

It is working for other fields without any problems as seen below:

enter image description here

Upvotes: 1

Views: 7876

Answers (2)

Poovizhi
Poovizhi

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

CodingYoshi
CodingYoshi

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

Related Questions