将2个ComboBox绑定到Dictionary,然后将ComboBox绑定到彼此

时间:2010-06-25 18:34:20

标签: c# wpf data-binding

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

将初始值预先填充到组合框“A”和“A”中相对容易。 “B”。这是双向约束,让我感到难过。

这是我填充词典的VM:

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

这是我绑定到Dictionary的初始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>

任何想法?
提前谢谢,
--ed

1 个答案:

答案 0 :(得分:0)

我想出了一部分。以下内容将使两个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来获得可编辑的方面。