【问题标题】:Defining a DataTemplate for a KeyValuePair为 KeyValuePair 定义 DataTemplate
【发布时间】:2015-01-18 08:39:54
【问题描述】:

我正在尝试将 KeyValuePair<int,MyClass> 指定为 WPF 中 DataTemplate 的数据类型。 KeyValuePair 来自 ObservableDictionary 对象(如果相关,我正在使用 Dr WPF's implementation

使用How to reference a generic type in the DataType attribute of a HierarchicalDataTemplate?,我能够得到一些接近的东西,但是,我遇到了编译器错误。

我需要能够为 KeyValuePair 定义 HierarchicalDataTemplate,以便我可以在其下方的 TreeView 中创建另一个叶子,其中包含一个集合,该集合是 Dictionary 的 Value 对象的一部分。

XAML 很简单:

<HierarchicalDataTemplate DataType="{local:GenericKeyValuePairType  
                                     KeyType=sys:Int32, 
                                     ValueType=local:MyClass}" 
                          ItemsSource="{Binding Path=Value.MyList}" />

而 GenericKeyValuePairType 是一个 MarkupExtension

public class GenericKeyValuePairType : MarkupExtension
{
    public Type KeyType { get; set; }
    public Type ValueType { get; set; }


    public GenericKeyValuePairType() { }
    public GenericKeyValuePairType(Type keyType, Type valueType)
    {
        KeyType = keyType;
        ValueType = valueType;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return typeof(KeyValuePair<,>).MakeGenericType(this.KeyType, this.ValueType);
    }
}

当我这样做时,Visual Studio 指出这是无效的。具体错误是:

字典的键不能是“TreeViewBindingTest.GenericKeyValuePairType”类型。仅支持 String、TypeExtension 和 StaticExtension。

我正在尝试做的事情是否可能?如果是这样,有没有更好的方法?

【问题讨论】:

  • 在您链接到的线程中有一个用于字典的 xaml 示例。为什么您不能使用该实现?我可能会误解你想要做什么。
  • @Default 我正在使用它,但我需要为该字典中的 KeyValuePairs 定义一个 HierarchicalDataTemplate,因为 Value 对象有另一个集合,它将成为 TreeView 中的另一个叶子。所以我需要能够定义它下面的结构。我尝试连接到 Values 属性,该属性确实有效,但由于无法观察到 Values 集合,因此对 Dictionary 的任何更改都不会显示在 TreeView
  • 在您的HierarchicalDataTemplate 中,您将MyList 绑定到ItemsSource。但是 KeyValuePair 没有 MyList 属性。 MyClass 可以是模板的来源吗?
  • @IlVic 应该是 Value.MyList。创建示例时出现拼写错误。

标签: c# wpf key-value hierarchicaldatatemplate


【解决方案1】:

在我看来,使用 KeyValuePair 作为 TreeViewItem 的 DataContext 是不正确的。 KeyValuePair 是密封的,所以不能实现INotifyPropertyChanged 接口。 此外,您不能使用您的 GenericKeyValuePairType 扩展,因为编译器认为您想将该对象用作 DataType(请阅读 here 了解更多信息)。

确实,您的模型是 MyClass 对象(您确认 MyList 属性属于它)。在这种情况下,您的 DataTemplate 将是:

<HierarchicalDataTemplate DataType="{x:Type local:MyClass}" 
                          ItemsSource="{Binding Path=MyList}" />

我相信它在概念上更正确。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    相关资源
    最近更新 更多