ItemsControl不显示我的项目

本文关键字:项目 我的 显示 ItemsControl | 更新日期: 2023-09-27 17:50:56

我正试图与ItemsControl和CompositeCollection一起工作,以在画布中显示不同的形状,但绑定有一些问题。现在我在画布上只看到"(Collection)"这个文本,这让我觉得我在尝试显示一个集合。

我不知道我是否对我的资源有问题,或者我只是在这里想错了(比如试图显示整个集合而不是每个项目),但会对一些指针感到高兴。

如果我改变"ItemsControl。"资源"到"ItemsControl"。它显示列表中的第一个项目,我只能使用一个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
        });
    }
}

ItemsControl不显示我的项目

你不能直接将Collection添加到CompositeCollection中,但你必须将它包装到CollectionContainer中:

 GraphData = new CompositeCollection { 
     new CollectionContainer { Collection = Axles }
 };