【问题标题】:ItemsControl don't display my itemsItemsControl 不显示我的项目
【发布时间】: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
        });
    }
}

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    您不能将 Collection 直接添加到 CompositeCollection,而必须将其包装到 CollectionContainer 中:

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

    【讨论】:

    • 是的,因为集合属性最初为空,所以您需要将项目包装在一个显式元素中,如上所示实例化集合。
    • Acutally 这不起作用,当我这样做并使用 ItemControl.Resources 时,我只得到一个小文本(整个命名空间 + 类名)。碰巧知道为什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    相关资源
    最近更新 更多