2016-02-18 80 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' –