微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 将Shapes.Path项绑定到ItemsControl

我一直试图找出如何绑定ObservableCollection< FrameworkElements>到一个ItemsControl.我有一个现有的项目,它严重依赖于后面的代码和canvas没有绑定,我试图更新以使用mvvm和prism.

ObservableCollection将填充许多Path项.它们是由我使用的外部库生成的.当我手动操作画布本身时,库正常运行.

以下是viewmodel代码的片段:

ObservableCollection<FrameworkElement> _items;
    ObservableCollection<FrameworkElement> Items
    {
        get { return _items; }
        set
        {
            _items = value;
            this.NotifyPropertyChanged("Items");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
        }
    }

支持XAML

<ItemsControl ItemsSource="{Binding Items}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas x:Name="canvas" IsItemsHost="True">
                        <Canvas.Background>
                            <SolidColorBrush Color="White" Opacity="100"/>
                        </Canvas.Background>

                    </Canvas>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Path/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

我遇到的问题是Path永远不会画画.关于我哪里出错以及从哪里开始调试过程的任何建议?

解决方法

您的视图模型应包含Path的抽象表示,例如

public class PathData
{
    public Geometry Geometry { get; set; }
    public Brush Fill { get; set; }
    public Brush stroke { get; set; }
    public double strokeThickness { get; set; }
    // ... probably more stroke-related properties
}

如果你现在有一个PathData对象的集合,如

public ObservableCollection<PathData> Paths { get; set; }

你的ItemsControl可以有一个Itemstemplate,如下所示:

<ItemsControl ItemsSource="{Binding Paths}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Path Data="{Binding Geometry}" Fill="{Binding Fill}"
                  stroke="{Binding stroke}" strokeThickness="{Binding strokeThickness}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

您现在将添加PathData实例,如下所示:

Paths.Add(new PathData
{
    Geometry = new RectangleGeometry(new Rect(100,100,100)),Fill = Brushes.AliceBlue,stroke = Brushes.Red,strokeThickness = 2
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐