2017-09-22 43 views
0

我試圖使用CompositeCollection在一個itemsControl中顯示不同的集合。我爲不同的類類型創建了多個DataTemplates。但是,該程序顯示class.ToString()而不是數據模板。根據this answer,我指定了{x:Type},但它不起作用。我錯過了什麼?CompositeCollection的DataTemplate不起作用

這裏是XAML:

<Window x:Class="TestCompositeConnection.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:TestCompositeConnection" 
     mc:Ignorable="d" 
     Title="MainWindow" 
     Height="350" 
     Width="525"> 
    <Grid> 
     <ListBox Name="myListBox" 
       Height="300" 
       Width="200" 
       Background="White"> 
      <ListBox.Resources> 
       <DataTemplate DataType="x:Type local:MyRectangle"> 
        <WrapPanel> 
         <TextBlock Text="{Binding Width}"></TextBlock> 
         <TextBlock Text="{Binding Height}"></TextBlock> 
        </WrapPanel> 
       </DataTemplate> 
       <DataTemplate DataType="x:Type local:MyLine"> 
        <StackPanel> 
         <TextBox Text="{Binding EndX}"></TextBox> 
         <TextBox Text="{Binding EndY}"></TextBox> 
        </StackPanel> 
       </DataTemplate> 
      </ListBox.Resources> 
     </ListBox> 
    </Grid> 
</Window> 

這裏是後面的代碼:

public partial class MainWindow : Window 
    { 
     public CompositeCollection Data { get; set; } 

     public ObservableCollection<MyRectangle> Rects { get; set; } 
     public ObservableCollection<MyLine> Lines { get; set; } 

     public MainWindow() 
     { 
      InitializeComponent(); 

      Data = new CompositeCollection(); 

      Rects = new ObservableCollection<MyRectangle>(); 
      Lines = new ObservableCollection<MyLine>(); 

      Rects.Add(new MyRectangle 
      { 
       X = 100, 
       Y = 100, 
       Width = 100, 
       Height = 100 
      }); 

      Lines.Add(new MyLine 
      { 
       StartX = 200, 
       StartY = 3, 
       EndX = 300, 
       EndY = 100 
      }); 

      Data.Add(new CollectionContainer() { Collection = Rects }); 
      Data.Add(new CollectionContainer() { Collection = Lines }); 

      myListBox.ItemsSource = Data; 
     } 
    } 

回答

0

嘗試把大括號中x:Type屬性值圍繞:

<DataTemplate DataType="{x:Type local:MyRectangle}"> 
    <WrapPanel> 
     <TextBlock Text="{Binding Width}"></TextBlock> 
     <TextBlock Text="{Binding Height}"></TextBlock> 
    </WrapPanel> 
</DataTemplate> 
<DataTemplate DataType="{x:Type local:MyLine}"> 
    <StackPanel> 
     <TextBox Text="{Binding EndX}"></TextBox> 
     <TextBox Text="{Binding EndY}"></TextBox> 
    </StackPanel> 
</DataTemplate> 
+0

是的,我剛剛發現這個愚蠢的錯誤我自己...謝謝...我已經花了數小時在這... – Siamca

相關問題