【问题标题】:How to do Two Way binding within two combo boxes in Silverlight如何在 Silverlight 中的两个组合框中进行双向绑定
【发布时间】:2012-08-22 06:25:31
【问题描述】:

在一个项目中,我展示了两个 ComboBoxes,比如说 ComboBox1 和 ComboBox2。我将 ComboBox 与 KeyValue 对绑定在一起 让我们说 dictionary1 如下所示。

ComboBox1.ItemsSource = dictionary1 ;
ComboBox1.SelectedItem = ComboBox1.Items[0];

//Setting the Item Source of Patient Name Combo Box.
ComboBox2.ItemsSource = dictionary1 ;
ComboBox2.SelectedItem = ComboBox2.Items[0];

在 XAML 部分,我在 Dictionary 的 CombBox1 中显示 Key,在 ComboBox2 中显示 Value,如下所述:-

<ComboBox
       x:Name             ="ComboBox1"
       DisplayMemberPath  ="Key"
       SelectedValue      ="{Binding Source=ComboBox2, Path=DisplayMemberPath, Mode=TwoWay}"/>

<ComboBox
       x:Name              ="ComboBox2"
       DisplayMemberPath   ="Value"
       SelectionChanged    ="ComboBox2_SelectionChanged"
       />

目标:- 如果我更改 ComboBox1 中的选择,那么它应该会影响 ComboBox2.SelectedItem 的相应值,如果我更改 ComboBox2 中的选择,那么它应该会影响 ComboBox1.SelectedItem 中的相应键值。

谁能告诉我上述代码中的错误在哪里,或者请帮助我完成上述目标。提前致谢。

【问题讨论】:

  • 您在绑定时出错。组合框 2 的 DisplayMemberPath 包含字符串值“Value”,因此在您尝试设置类似 combobox1.SelectedValue = combobox1.DisplayMemberPath 的内容时,这是没有意义的。

标签: c# wpf silverlight xaml data-binding


【解决方案1】:

这应该可以工作

<ComboBox
       x:Name             ="ComboBox1"
       DisplayMemberPath  ="Key"
       SelectedItem      ="{Binding ElementName=ComboBox2, Path=SelectedItem, Mode=TwoWay}"/>

<ComboBox
       x:Name              ="ComboBox2"
       DisplayMemberPath   ="Value"
       />

【讨论】:

  • dbaseman,我认为应该有Mode=TwoWay,否则对我不起作用。感谢大家快速回答
  • dbaseman,在 SL 中默认模式具有 OneWay 绑定,不像在 WPF TwoWay 中。
【解决方案2】:

我至少可以看出两个问题:

  1. 需要是 ElementName 而不是 Source
  2. 应该是 Path 而不是 DisplayMemberPath

我认为这应该可行:

<ComboBox
   x:Name             ="ComboBox1"
   DisplayMemberPath  ="Key"
   SelectedValue      ="{Binding ElementName=ComboBox2, Path=SelectedValue}"/>

<ComboBox
   x:Name             ="ComboBox2"
   DisplayMemberPath  ="Value" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2019-09-15
    • 1970-01-01
    • 2020-01-15
    • 2013-06-20
    相关资源
    最近更新 更多