将x:array绑定到property

时间:2012-11-26 16:38:14

标签: c# wpf binding datatemplateselector

由于我经常使用TemplateSelectors区分基于Type的模板,因此我尝试编写一个TemplateSelector,它具有保存类型/模板关系的属性。

我尝试使用x:Array在XAML中设置此属性。这不起作用,因为VS抱怨x:Array不是一个实现IEnumerable的类,根据它应该的文档

MSDN:

  

但是x:Array也可以用于使用XAML填充某些属性,这些属性将通用集合支持接口或类作为其结构化属性内容,例如IEnumerable。

这里是相应的代码行

TemplateSelector

public class TypeMatchDataTemplateSelector : DataTemplateSelector
{
    public TypeTemplate[] Templates { get; set; }

    ...
}

public class TypeTemplate
{
    public Type Type { get; set; }
    public DataTemplate Template { get; set; }
}

在XAML中使用

<x:Array Type="ct:TypeTemplate" x:Key="fooTemplates">
    <ct:TypeTemplate
        Type="{x:Type logic:NamedRegisterInformation}"
        Template="{StaticResource RegisterListTemplate}" />
    <ct:TypeTemplate
        Type="{x:Type logic:AddressedRegisterInformation}"
        Template="{StaticResource RegisterListTemplate}" />
</x:Array>

<ct:TypeMatchDataTemplateSelector
    x:Key="foo"
    Templates="{StaticResource fooTemplates}"/>
...
...
<ListBox ItemTemplate="{StaticResource blub}">

使用的类型和模板应该是正确的。如果我执行代码,我会在运行时获得此异常:

  

无法将属性“模板”中的值转换为类型对象   'EP3_gui.UI.ContentTemplates.TypeTemplate []'。对象类型   'System.Windows.Markup.ArrayExtension'无法转换为类型   'EP3_gui.UI.ContentTemplates.TypeTemplate []'。对象'blub'出错   在标记文件'EP3_gui; component / ui / readmsfrcontrol.xaml'第36行   第11位。

我的错误可能存在的任何提示?

1 个答案:

答案 0 :(得分:1)

你为什么要这么努力?我的意思是还有很多其他方法可以成为一名优秀的程序员!我只是在开玩笑。

你可以简单地写两个"DataTemplate"并根据"DataType"这样过滤它们:

<Window.Resources>

    <DataTemplate DataType="x:Type logic:AddressedRegisterInformation" ></DataTemplate>

    <DataTemplate DataType="x:Type logic:NamedRegisterInformation" ></DataTemplate>

</Window.Resources>
<ListBox ItemsSource="{Binding}" />

你为什么不这样做?而不是尝试使用复杂的自定义"TemplateSelector",这可能会导致许多问题,如您提到的问题。通过这种方式,WPF将执行所有选择,然后您将"Object"数组绑定到"ItemsSource"

希望有所帮助

相关问题