简体   繁体   English

c#和wpf-选择另一个comboBox的项目时如何更改comboBox项

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

I have an issue with two comboBoxes in wpf. 我在wpf中有两个comboBoxes的问题。 The first and second comboBoxes have the same values of items like here: 第一个和第二个comboBoxes具有相同的项目值,如下所示:

ComboBox1: 组合框1:
Toyota 丰田汽车
Golf 高尔夫球
Mini 微型

ComboBox2 : 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. 因此,当我选择ComboBox1的项目“ Toyota”时,我希望ComboBox2自动更改此选定项目的值,反之亦然。 How to do this in C#? 如何在C#中做到这一点? Or should I bind comboBox1 to ComboBox2? 还是应该将comboBox1绑定到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

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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