简体   繁体   中英

WPF - change the selected Item of one combobox to the selected item of another combobox

I have two combo boxes in my .xaml file. I would call the first combobox "main combo box ". The other combobox also contains the same set of values as in the the first main combobox.

When I change the selection in the first combobox, I want the selection of the other combobox to be changed to the same value.

I have done it like in the following.

In my viewmodel, I have the following.

  private <MyClass> _firstComboBoxSelection;
  public <MyClass>  FirstComboboxSelection
  {
         set { _firstComboBoxSelection=value; }
         get { return _firstComboBoxSelection ; }

  }

   private <MyClass> _secondComboBoxSelection;
   public <MyClass>  SecondComboboxSelection
   {
         set { _secondComboBoxSelection=value; }
         get { return _secondComboBoxSelection ; }

    }

The comboboxes are like in the following.

       <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 is a ObservableCollection of MyClass . MyClass contains the property Name . In my .xaml.cs file I have the following.

  private void cmbFirst_SelectionChanged(...)
  {

        _secondComboBoxSelection=_firstComboBoxSelection;
  }

But it does not change the second combo box as I want it to. Can someone help me to figure out where I have gone wrong ?

In you second combo box change

  <ComboBox SelectedItem="{Binding SecondComboboxSelection}"

to

 <ComboBox SelectedItem="{Binding FirstComboboxSelection}"

You can also try to use SelectedValuePath like this

  <ComboBox Name="cmbFirst"
                 SelectionChanged="cmbFirst_SelectionChanged"
                 SelectedItem="{Binding FirstComboboxSelection,Mode=TwoWay}"
                 ItemSource="{Binding MyData}"
                 SelectedValuePath="Name" 
                 DisplayMemberPath="Name" />

and in code you can do something like this -

  private <MyClass> _firstComboBoxSelection;
  public <MyClass>  FirstComboboxSelection
  {
         set { _firstComboBoxSelection=value;
                 OnPropertyChanged(_firstComboBoxSelection ); }
         get { return _firstComboBoxSelection ;
                }

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM