根据类型选择数据模板

Selecting a data template based on type

我已经声明了以下类型:

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

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

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

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

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

我做错了什么?

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

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