基于类型选择数据模板

16

我已经声明了以下类型:

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>
我期望看到的是一个红色正方形和一个蓝色正方形,但实际看到的是下面这个图像: enter image description here 我做错了什么?

1
我认为您实际上想要的是DataTemplateSelector - Chris W.
@ChrisW。直接从该链接中获取:“……当您有多个相同类型对象的DataTemplate并且希望根据每个数据对象的属性提供自己的逻辑来选择要应用的DataTemplate时,请创建DataTemplateSelector。请注意,如果您具有不同类型的对象,则可以在DataTemplate上设置DataType属性。” - kkyr
抱歉,我在想ItemTemplateSelector,也许我不应该在这里,因为这是自冬季以来的第一个好天气,我的思维已经飘到别处了,我甚至没有认真看完整个问题。春天的狂欢,干杯! - Chris W.
你也可以使用DataTemplateSelector来实现。MSDN参考Stackoverflow参考 - garenyondem
1个回答

28

您遇到的问题可能是由于 XAML 的微妙工作方式引起的。具体来说,您需要将 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>

非常感谢,它完美地运行了。不过你忘记了大括号 ({x:Type local:ClassOne})。你有任何想法为什么我之前使用的方法没有起作用吗? - kkyr
5
你的代码无法正常工作,是因为 DataTemplate.DataType 属性的类型是 object,而非像 Style.TargetType 那样是 Type 类型。因此,local:ClassOne 被解释为字符串,并且不能被隐式转换为 Type 类型。 - Clemens
2
x:Type 的作用就像 typeof() 运算符一样,所以您需要传递给 DataType 的是一个 Type 而不是您的类的名称。即使 文档 表明它接受 object,示例也没有使用 x:Type - Amadeusz Wieczorek
这个在 UWP 中能以同样的方式完成吗? - IronHide

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接