根据类型选择数据模板 [英] Selecting a data template based on type

查看:87
本文介绍了根据类型选择数据模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我声明了以下类型:

public interface ITest { }
public class ClassOne : ITest { }
public class ClassTwo : ITest { }

在我的视图模型中,我声明并初始化以下集合:

In my viewmodel I'm declaring and initializing the following collection:

public class ViewModel
{
    public ObservableCollection<ITest> Coll { get; set; } = new ObservableCollection<ITest>
    {
        new ClassOne(),
        new ClassTwo()
    };  
}

在我看来,我声明以下ItemsControl

In my view I'm declaring the following ItemsControl

<ItemsControl ItemsSource="{Binding Coll}">
    <ItemsControl.Resources>
        <DataTemplate DataType="local:ClassOne">
            <Rectangle Width="50" Height="50" Fill="Red" />
        </DataTemplate>
        <DataTemplate DataType="local:ClassTwo">
            <Rectangle Width="50" Height="50" Fill="Blue" />
        </DataTemplate>
    </ItemsControl.Resources>
</ItemsControl>

我希望看到的是一个红色的正方形,然后是一个蓝色的正方形,相反,我看到的是以下内容:

What I expect to see is a red square followed by a blue square, instead what I see is the following:

我在做什么错了?

推荐答案

您的问题可能是由XAML的精细工作引起的.具体来说,您需要将Type传递给DataType,但是您传递的是带有类型名称的字符串.

Your issue might be caused by finnicky workings of XAML. Specifically, you need to pass Type to DataType, but you were passing a string with the name of the type.

使用x:Type装饰DataType的值,如下所示:

Use x:Type to decorate the value of DataType, like so:

<ItemsControl ItemsSource="{Binding Coll}">
    <ItemsControl.Resources>
        <DataTemplate DataType="{x:Type local:ClassOne}">
            <Rectangle Width="50" Height="50" Fill="Red" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:ClassTwo}">
            <Rectangle Width="50" Height="50" Fill="Blue" />
        </DataTemplate>
    </ItemsControl.Resources>
</ItemsControl>

这篇关于根据类型选择数据模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆