【问题标题】:Selecting a data template based on type根据类型选择数据模板
【发布时间】:2016-05-31 07:24:12
【问题描述】:

我已经声明了以下类型:

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>

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

我做错了什么?

【问题讨论】:

  • 我认为你实际上想要DataTemplateSelector
  • @ChrisW。直接来自该链接:"... 当您为同一类型的对象拥有多个 DataTemplate 并且您希望提供自己的逻辑以根据每个数据对象的属性选择要应用的 DataTemplate 时,请创建一个 DataTemplateSelector . 请注意,如果您有不同类型的对象,您可以在 DataTemplate 上设置 DataType 属性。"
  • 对不起伙计,我在想ItemTemplateSelector,反正我可能不应该在这里,自从冬天以来的第一个美好的一天,我的思绪在别处,我想我什至没有真正看过整个问题大声笑。春暖花开,干杯。
  • 您也可以使用 DataTemplateSelector。 MSDN ref.Stackoverflow ref.

标签: c# wpf xaml mvvm datatemplate


【解决方案1】:

您的问题可能是由 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>

【讨论】:

  • 工作得很好,谢谢,但是你省略了花括号({x:Type local:ClassOne})。知道为什么我使用的东西不起作用吗?
  • @kyriacos_k 你的不工作,因为DataTemplate.DataType 属性是object 类型(而不是例如Style.TargetType,它是Type 类型)。因此local:ClassOne 被解释为字符串,而不是隐式转换为Type
  • x:Type 就像typeof() 操作符一样,所以你传入DataType Type 而不是你的类名。 - 即使documentation 声明它需要object 并且示例不使用x:Type
  • 这可以用 uwp 相同的方式完成吗?
猜你喜欢
  • 2022-11-10
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 2021-02-25
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多