wpf - 如何绑定(bind)到字典中的项目?

标签 wpf xaml data-binding dictionary datatemplate

我在 C# 的 WPF 应用程序中使用来自 Telerik 的 RadCarousel 控件。 RadCarousel 与 GridView 类似,因为它绑定(bind)到集合并显示集合中的每个项目(因此我的问题并非特定于 Telerik 或 RadCarousel)。

我使用 DataTemplate 来指定每条记录的显示方式。

如果我这样做,效果很好:

<DataTemplate>
    <TextBlock Text="{Binding Path=oMySubObject.TheAmount}" />
</DataTemplate>

但是如果我需要指向字典中的某个项目怎么办?

<DataTemplate>
    <TextBlock Text="{Binding Path=myDictionaryOfSubObjects[TheCurrentIndex].TheAmount}" />
</DataTemplate>

这我无法工作,也不知道如何。基本上...我需要在运行时指定索引,当索引更新时,绑定(bind)也会更新。

有什么建议吗?

最佳答案

<Window.Resources>
  <NAMESPACEWHERECONVERTERRESIDES:DictionaryConverter x:Key="cDictionaryConverter"/>
</WindowResources>


    <TextBlock Text="{Binding Path=myDictionaryOfSubObjects, Converter={StaticResource cDictionaryConverter}}"/>

//类似这样的:

[ValueConversion(typeof(Dictionary), typeof(string))]
public class DictionaryConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
         Dictionary<type, type> dict = value as Dictionary<type, type>; 
         return dict[CurrentIndex].TheAmount; 
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return 0;
    }
}

关于wpf - 如何绑定(bind)到字典中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9184627/

相关文章:

c# - 数据绑定(bind)到对象 - 如何取消数据源更改

c# - 从其他窗口刷新组合框列表,MVVM

c# - 通过 ComboBox 更改 RichTextBox Selection 的字体大小无法正常工作

WPF 与 Windows WebBrowser 控件

c# - 如何在 xaml 中将字符串转换为 Uri?

android - 使布局在所有设备上看起来都不错

.net - WPF说,数据项不为空时为空

c# - 根据节点类型不同的 WPF Treeview 图标

c# - 在 WPF 中选择静态 ComboBoxItems 的项目

c# - Blazor 中的数据绑定(bind) : How to propagate values out of a component?