【发布时间】:2015-08-09 17:24:50
【问题描述】:
我正在尝试使用 ItemsControl 和 CompositeCollection 在画布中显示不同的形状,但在绑定时遇到了一些问题。现在我只在我的画布中看到文本“(集合)”,这让我觉得我正在尝试显示一个集合。
我不知道我的资源是否有问题,或者我只是在这里想错了(比如尝试显示整个集合而不是每个项目),但我会很高兴有一些指针。
如果我将“ItemsControl.Resources”更改为“ItemsControl.ItemTemplate”,它会显示列表中的第一项,而我只能使用一个 DataTemplate,这样就不好了。
代码如下所示,XAML:
<Grid>
<ItemsControl ItemsSource="{Binding GraphData}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.Resources>
<DataTemplate DataType="model:Axle">
<Line X1="{Binding StartX}" X2="{Binding EndX}" Y1="{Binding StartY}" Y2="{Binding EndY}" Stroke="Black" StrokeThickness="2"/>
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
</Grid>
在我的 ViewModel 中:
public class GraphViewModel : ViewModelBase
{
public ObservableCollection<Axle> Axles { get; set; }
public CompositeCollection GraphData { get; set; }
public GraphViewModel()
{
Axles = new ObservableCollection<Axle>();
GraphData = new CompositeCollection { Axles };
InitializeAxles();
}
private void InitializeAxles()
{
//X-axle
Axles.Add(new Axle
{
StartX = 50,
StartY = 530,
EndX = 530,
EndY = 530
});
//Y-axle
Axles.Add(new Axle
{
StartX = 50,
StartY = 0,
EndX = 50,
EndY = 530
});
}
}
【问题讨论】: