根据类型选择数据模板

ksk*_*cou 10 c# wpf xaml datatemplate mvvm

我已经声明了以下类型:

public interface ITest { }
public class ClassOne : ITest { }
public class ClassTwo : ITest { }
Run Code Online (Sandbox Code Playgroud)

在我的viewmodel中,我正在声明并初始化以下集合:

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

在我看来,我宣布以下内容 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>
Run Code Online (Sandbox Code Playgroud)

我期待看到的是一个红色方块,后面是一个蓝色方块,而我所看到的是以下内容:

在此输入图像描述

我究竟做错了什么?

Ama*_*rek 17

您的问题可能是由XAML的辛苦工作引起的.具体来说,您需要传递TypeDataType,但是您传递的是具有该类型名称的字符串.

使用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>
Run Code Online (Sandbox Code Playgroud)

  • @kyriacos_k你的工作不正常,因为`DataTemplate.DataType`属性的类型是`object`(而不是像`Style.TargetType`,它是`Type`类型).因此`local:ClassOne`被解释为字符串而不是隐式转换为`Type`. (3认同)
  • `x:Type`就像`typeof()`运算符一样,所以你传入`DataType`一个`Type`而不是你的类的名字. - 即使[文档](https://msdn.microsoft.com/en-us/library/system.windows.datatemplate.datatype%28v=vs.110%29.aspx)声明它需要`object`和示例don不要使用`x:Type` (2认同)