加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:15:32 所属栏目:百科 来源:网络整理
导读:我一直试图找出如何绑定ObservableCollection FrameworkElements到一个ItemsControl.我有一个现有的项目,它严重依赖于后面的代码和canvas没有绑定,我试图更新以使用mvvm和prism. ObservableCollection将填充许多Path项.它们是由我使用的外部库生成的.当我手
我一直试图找出如何绑定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
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读