【发布时间】: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