【问题标题】:Binding 2 ComboBox to a Dictionary, then binding the ComboBoxes to each other将 2 个 ComboBox 绑定到字典,然后将 ComboBox 相互绑定
【发布时间】:2011-03-08 10:10:14
【问题描述】:

我有一个从 int 到 char 的字典(与该 int 相关的十进制和 ASCII 字符)。我想要两个可编辑的组合框,它们预先填充了初始值。如果用户从 ComboBox “A”(dict 键)中选择了一个值,我希望将 dict 值填充到 ComboBox “B”中,反之亦然。

将初始值预填充到组合框“A”和“B”中相对容易。难倒我的是双向绑定。

这是我填充字典的虚拟机:

    private void InitializeSpearatorsDictionaries()
    {
        // comma, semicolon, vertical pipe, tilda
        int[] fields = { 44, 59, 124, 126 };
        foreach (int f in fields)
        {
            FieldDict.Add(f, Convert.ToChar(f));
        }
    }
    public IDictionary<int, char> FieldDict
    {
        get
        {
            if (_fieldDict == null)
            {
                _fieldDict = new Dictionary<int, char>();
            }
            return _fieldDict;
        }
    }

这是我绑定到字典的初始 XAML(仍然没有问题)

<StackPanel>
<ComboBox x:Name="cbFieldChar" ItemsSource="{Binding Path=FieldDict}" SelectedIndex="0" DisplayMemberPath="Key" SelectedValuePath="Value" IsEditable="True" />
<ComboBox x:Name="cbFieldDecimal" ItemsSource="{Binding Path=FieldDict}" SelectedIndex="0" DisplayMemberPath="Value" SelectedValuePath="Key" IsEditable="True" />
</StackPanel>

最初,我有 ItemsSource = {Binding Path=FIeldDict.Keys} 和 {Binding Path=FieldDict.Values},在这种情况下,我不需要 DisplayMemberPath 和 SelectedValuePath 属性,但尝试获得双向工作,我重新设计了它(两种方法都适用于字典的初始加载)。

这是在两个 ComboBox 之间进行双向工作的最新尝试

<StackPanel>
<ComboBox x:Name="cbFieldChar" ItemsSource="{Binding Path=FieldDict}" SelectedIndex="0" DisplayMemberPath="Key" SelectedValuePath="Value" IsEditable="True" />
<ComboBox x:Name="cbFieldDecimal" ItemsSource="{Binding Path=FieldDict}" SelectedIndex="0" DisplayMemberPath="Value" SelectedValuePath="Key" IsEditable="True" SelectedValue="{Binding ElementName=cbFieldChar, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Path=ItemsSource.Value}" />
</StackPanel>

有什么想法吗?
在此先感谢,
--埃德

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    我想出了一部分。以下将用于将两个 ComboBox 与其中已存在的值同步。

    <ComboBox x:Name="cbFieldChar" ItemsSource="{Binding Path=FieldDict}" SelectedIndex="0" DisplayMemberPath="Value" SelectedValuePath="Key" IsEditable="True" />
    <ComboBox x:Name="cbFieldDecimal" ItemsSource="{Binding Path=FieldDict}" SelectedIndex="0" DisplayMemberPath="Key" SelectedValuePath="Value" IsEditable="True" SelectedValue="{Binding ElementName=cbFieldChar, Path=SelectedValue}" />
    

    我将尝试使用 ValueConverter 来实现可编辑方面。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 2021-10-03
      • 2016-12-12
      • 2013-10-21
      • 2014-10-10
      • 2011-05-16
      • 2011-11-11
      相关资源
      最近更新 更多