wpf 根据类型选择数据模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35493146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:41:01  来源:igfitidea点击:

Selecting a data template based on type

c#wpfxamlmvvmdatatemplate

提问by kskyriacou

I've declared the following types:

我已经声明了以下类型:

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()
    };  
}

In my view I'm declaring the following ItemsControl

在我看来,我声明如下 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:

我希望看到的是一个红色方块后跟一个蓝色方块,而不是我看到的是以下内容:

enter image description here

在此处输入图片说明

What am I doing wrong?

我究竟做错了什么?

回答by Amadeusz Wieczorek

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

您的问题可能是由 XAML 的工作原理引起的。具体来说,您需要传递TypeDataType,但是您传递的是一个带有类型名称的字符串。

Use x:Typeto decorate the value of DataType, like so:

使用x:Type装饰的价值DataType,就像这样:

<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>