我正在尝试使用CompositeCollection
在一个itemsControl中显示不同的集合。我为不同的类类型创建了多个DataTemplates。但是,程序显示class.ToString()而不是数据模板。根据{{3}},我已指定类型 {x:Type} ,但它不起作用。我错过了什么吗?
这是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 :(得分: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>