Question

Since I often use TemplateSelectors that distinguish between templates based on Type, I tried to write a TemplateSelector that has a property to hold the type/template relationship.

I tried to use x:Array to set this property in XAML. This does not work since VS complains that x:Array is not a class that implements IEnumerable, which according to the documentation it should

MSDN:

But x:Array can also be useful for populating certain properties using XAML that take general collection support interfaces or classes as their structured property content, for instance as IEnumerable.

Here the corresponding code lines

TemplateSelector

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

    ...
}

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

Use in 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}">

The used Types and Templates should be correct. If I execute the code I get this Exception at runtime:

Cannot convert the value in attribute 'Templates' to object of type 'EP3_gui.UI.ContentTemplates.TypeTemplate[]'. Object of type 'System.Windows.Markup.ArrayExtension' cannot be converted to type 'EP3_gui.UI.ContentTemplates.TypeTemplate[]'. Error at object 'blub' in markup file 'EP3_gui;component/ui/readmsfrcontrol.xaml' Line 36 Position 11.

Any hints where my error might lie?

Was it helpful?

Solution

Why are you making your life so hard? I mean there are many other ways to be a good programmer! I was just kidding.

You can simply write two "DataTemplate"s and filter them based on their "DataType" like this:

<Window.Resources>

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

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

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

Why don't you do this? instead of trying to use complicated custom "TemplateSelector" that might cause you many problems like the one you mentioned. This way WPF will do all the selection things and you sit, bind an array of "Object" to the "ItemsSource".

Hope it helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top