简体   繁体   中英

c# and wpf - how to change comboBox item when select item of another comboBox

I have an issue with two comboBoxes in wpf. The first and second comboBoxes have the same values of items like here:

ComboBox1:
Toyota
Golf
Mini

ComboBox2 :
Toyota
Golf
Mini

So when I select an item "Toyota" of ComboBox1, I want ComboBox2 to automatically change value of this selected item and vica versa. How to do this in C#? Or should I bind comboBox1 to ComboBox2? I never do it before. Your code would be much appreciated. Thanks!!

If both ComboBox controls share same collection of items then on both of them set IsSynchronizedWithCurrentItem to True

<ComboBox IsSynchronizedWithCurrentItem="True" ... />

so for example it can look like this:

<StackPanel xmlns:sys="clr-namespace:System;assembly=mscorlib">
   <StackPanel.Resources>
       <x:Array Type="{x:Type sys:String}" x:Key="CarList">
           <sys:String>Toyota</sys:String>
           <sys:String>Golf</sys:String>
           <sys:String>Mini</sys:String>
       </x:Array>
   </StackPanel.Resources>
   <ComboBox IsSynchronizedWithCurrentItem="True" ItemsSource="{StaticResource CarList}"/>
   <ComboBox IsSynchronizedWithCurrentItem="True" ItemsSource="{StaticResource CarList}"/>
</StackPanel>

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