ListBox绑定一个类的Dictionary,在xaml中显示键和选择类对象而不是KeyValuePair。

问题描述 投票:0回答:1

我有一个 ListBox 我受制于一个 MyDictionary<string, MyClass> 在xaml中(DataContext 是正确设置)。)

<ListBox x:Name="MyListBox" 
SelectedIndex="0"
DataContext="{Binding ElementName=thiswindow}"
SelectedItem="{Binding SelectedMyClass}"
ItemsSource="{Binding Path=MyDictionary}"
SelectedValuePath="Value"
SelectionChanged="MyListBox_SelectionChanged"
DisplayMemberPath="Key">

我正在寻找。

  1. 显示键,已经实现。
  2. 返回所选类型的项目 MyClass.

由于 MyDictionary.Value 属于 MyClass 我有 SelectedValuePath="Value" 但似乎返回的选择对象的类型是 KeyValuePair<string, MyClass> 根据我得到的错误信息。

Cannot convert '[Test, MyClass]' from type 'KeyValuePair`2' to type 'MyClass' for 'en-US' culture with default
 conversions; consider using Converter property of Binding.

我发现唯一的解决办法是用 SelectionChanged 事件。

private void MyListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var tmp = (KeyValuePair<string, MyClass>)MyListBox.SelectedItem;
            SelectedMyClass= MyDictionary[tmp.Key];    
        }

我相信有一种方法可以在xaml中实现它 或者至少是一种更简洁的方式,同时继续使用 Dictionary 类。

也许只是多用了一个转换器吗,我缺少什么?

相关问题。在wpf中绑定一个字典中的类属性

c# wpf xaml dictionary data-binding
1个回答
1
投票

因为有SelectedValuePath,所以绑定SelectedValue而不是SelectedItem,这样就不需要处理选择事件(删除SelectionChanged处理方法)。

<ListBox x:Name="MyListBox" 
    SelectedIndex="0"
    DataContext="{Binding ElementName=thiswindow}"
    SelectedValue="{Binding SelectedMyClass}"
    ItemsSource="{Binding Path=MyDictionary}"
    SelectedValuePath="Value"
    DisplayMemberPath="Key">
© www.soinside.com 2019 - 2024. All rights reserved.