Databinding issue with ComboBox
When binding data to combobox, 3 items need to be set:
开发者_高级运维<ComboBox ItemsSource="{Binding MyList}" SelectedItem="{Binding MyItem}" DisplayMemberPath="MyName" />
Say ItemSource is list of Country
I set itemsource to right source firstly, it is fine. Then I set selectedItem to specific Country object, but it's not working.
Looks like all need to be set when ItemSource is setting.
How to resolve this problem?
UPDATE WITH WORKING CODE
Make sure you enable two-way binding on the SelectedItem.
<ComboBox ItemsSource="{Binding Path=Countries, Mode=OneWay}" SelectedItem="{Binding Path=SelectedCountry, Mode=TwoWay}" Height="23" HorizontalAlignment="Left" Margin="12,28,0,0" Name="comboBox1" VerticalAlignment="Top" Width="267" />
Here is what your context will look like:
public partial class MainPage : UserControl, INotifyPropertyChanged
{
public MainPage()
{
InitializeComponent();
this.Countries = new ObservableCollection<string> { "USA", "CAN" };
this.DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<string> Countries { get; set; }
private string _selectedCountry = null;
public string SelectedCountry
{
get { return _selectedCountry; }
set
{
_selectedCountry = value;
if( this.PropertyChanged != null )
this.PropertyChanged( this, new PropertyChangedEventArgs( "SelectedCountry" ) );
}
}
private void button1_Click( object sender, RoutedEventArgs e )
{
MessageBox.Show( "Selected Country: " + this.SelectedCountry );
}
}
精彩评论