将数据绑定到组合框时,需要设置3个项目:
<ComboBox ItemsSource="{Binding MyList}" SelectedItem="{Binding MyItem}" DisplayMemberPath="MyName" />
Say ItemSource是国家/地区列表
我首先将itemsource设置为right source,没关系。然后我将selectedItem设置为特定的Country对象,但它不起作用。
看起来在设置ItemSource时都需要设置。
如何解决此问题?
答案 0 :(得分:0)
使用工作代码更新
确保在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" />
以下是您的上下文:
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 );
}
}