我试图使用CompositeCollection在一个itemsControl中显示不同的集合。我为不同的类类型创建了多个DataTemplates。但是,该程序显示的是class.ToString()而不是数据模板。根据this answer,我已经指定了类型{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;
}
}发布于 2017-09-22 02:19:56
尝试将花括号放在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>https://stackoverflow.com/questions/46355831
复制相似问题