[英]WPF - change the selected Item of one combobox to the selected item of another combobox
我的.xaml文件中有兩個組合框。 我將第一個組合框稱為“主組合框”。 另一個組合框還包含與第一個主組合框相同的一組值。
當我在第一個組合框中更改選擇時,我希望另一個組合框的選擇更改為相同的值。
我已經完成了以下操作。
在我的視圖模型中,我有以下內容。
private <MyClass> _firstComboBoxSelection;
public <MyClass> FirstComboboxSelection
{
set { _firstComboBoxSelection=value; }
get { return _firstComboBoxSelection ; }
}
private <MyClass> _secondComboBoxSelection;
public <MyClass> SecondComboboxSelection
{
set { _secondComboBoxSelection=value; }
get { return _secondComboBoxSelection ; }
}
組合框如下所示。
<ComboBox Name="cmbFirst"
SelectionChanged="cmbFirst_SelectionChanged"
SelectedItem="{Binding FirstComboboxSelection,Mode=TwoWay}"
ItemSource="{Binding MyData}"
DisplayMemberPath="Name" />
<ComboBox SelectedItem="{Binding SecondComboboxSelection,Mode=TwoWay}"
ItemSource="{Binding MyData}"
DisplayMemberPath="Name" />
MyData是MyClass的ObservableCollection。 MyClass包含屬性Name 。 在我的.xaml.cs文件中,我有以下內容。
private void cmbFirst_SelectionChanged(...)
{
_secondComboBoxSelection=_firstComboBoxSelection;
}
但是它並沒有改變我想要的第二個組合框。 有人可以幫我弄清楚我哪里出了問題嗎?
在您第二個組合框更改中
<ComboBox SelectedItem="{Binding SecondComboboxSelection}"
至
<ComboBox SelectedItem="{Binding FirstComboboxSelection}"
您也可以嘗試像這樣使用SelectedValuePath
<ComboBox Name="cmbFirst"
SelectionChanged="cmbFirst_SelectionChanged"
SelectedItem="{Binding FirstComboboxSelection,Mode=TwoWay}"
ItemSource="{Binding MyData}"
SelectedValuePath="Name"
DisplayMemberPath="Name" />
在代碼中,您可以執行以下操作-
private <MyClass> _firstComboBoxSelection;
public <MyClass> FirstComboboxSelection
{
set { _firstComboBoxSelection=value;
OnPropertyChanged(_firstComboBoxSelection ); }
get { return _firstComboBoxSelection ;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.