将 WPF Canvas 子项绑定到 ObservableCollection [英] Binding WPF Canvas Children to an ObservableCollection

查看:77
本文介绍了将 WPF Canvas 子项绑定到 ObservableCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 WPF 应用程序中,我有一个 Canvas,我可以在其中进行一些绘图.早些时候我在后面的代码中处理了绘图,但现在我已将所有内容分解为 ViewModel.这给了我一些挑战..

In my WPF application I have a Canvas in which I do some drawing. Earlier I handled the drawing in the code behind, but now I've factored everything out to a ViewModel. This gives me some challenges..

我有一些包含笔画的 InkPresenter 对象.早些时候我在后面的代码中将它们作为孩子添加到画布中 - 像这样:

I have a few InkPresenter objects holding Strokes. Earier I added them as children to the Canvas in the code behind - like this:

// Build an InkPresenter: 
var someInkPresenter = BuildInkPresenter(..); 
//_myCanvas is the <Canvas> I want to display it in: 
_myCanvas.Children.Add(someInkPresenter); 

现在 - 不在包含 _myCanvas 的 XAML 的代码隐藏中构建 InkPresenter 我需要以不同的方式执行此操作.我想做的是创建一个 InkPresenter 并将其添加到一个集合中:

Now - not building the InkPresenter in the code-behind of the XAML that holds _myCanvas I need to do this differently. What I'd like to do is to create an InkPresenter and add it to a collection:

public ObservableCollection<InkPresenter> Drawings;

我现在的问题是如何将 Canvas 绑定到此 ObservableCollection - 并在添加到集合时显示 InkPresenter.我可以以某种方式使用数据绑定来实现这一点吗?

My problem now is how to bind the Canvas to this ObservableCollection - and have the InkPresenters displayed when added to the collection. Can I achieve this using Data Bindings somehow?

推荐答案

我认为您可以使用 ItemsControl + ItemsPanelTemplate.像这样:

I think you can do this with ItemsControl + ItemsPanelTemplate. Like this:

<ItemsControl ItemsSource="{Binding YourCollection}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

要阅读有关此方法的更多信息,请参阅 Dr.WPF:ItemsControl: A toZ (P 代表面板)

To read more about this approach refer to Dr.WPF: ItemsControl: A to Z (P is for Panel)

这篇关于将 WPF Canvas 子项绑定到 ObservableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆