2016-02-18 83 views
6

数据模板我已经声明了以下几种类型:选择基于类型

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](https://msdn.microsoft.com/en-us/library/system.windows.controls.datatemplateselector%28v=vs.110%29.aspx ) –

+0

@ChrisW。直接从该链接:_“...如果您有多个DataTemplate用于相同类型的对象,并且您想提供自己的逻辑以根据每个数据对象的属性选择要应用的DataTemplate,则创建一个DataTemplateSelector。* *请注意,如果您拥有不同类型的对象,则可以在DataTemplate **上设置DataType属性。“_ – kskyriacou

+0

对不起,正在考虑[ItemTemplateSelector](https://msdn.microsoft.com/en-us/library/ system.windows.controls.itemscontrol.itemtemplateselector%28v = vs.110%29.aspx),我可能不应该在这里,从冬天开始的美好的一天,我的思绪在别处,我不认为我什至实际上看着整个问题哈哈。春热,欢呼声。 –

回答

7

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

完美谢谢,您省略了花括号({x:Type local:ClassOne})。任何想法为什么我使用的是不工作? – kskyriacou

+1

@kyriacos_k您的工作不正常,因为DataTemplate.DataType属性的类型为object(而不是'Style.TargetType',它的类型为'Type')。因此'local:ClassOne'被解释为字符串,而不是隐式转换为'Type'。 – Clemens

+2

'x:Type'就像'typeof()'操作符一样,所以你将'Type'传入'DataType'而不是类的名字。 - 即使[文档](https://msdn.microsoft.com/en-us/library/system.windows.datatemplate.datatype%28v=vs.110%29.aspx)指出它需要'对象'和示例't use'x:Type' –