将WPF画布儿童绑定到ObservableCollection [英] Binding WPF Canvas Children to an ObservableCollection
问题描述
我有几个InkPresenter对象持有笔画。 Earier我将它们作为孩子添加到Canvas中,代码如下:
//构建一个InkPresenter:
var someInkPresenter = BuildInkPresenter(..);
// _ myCanvas是< Canvas>我想显示它:
_myCanvas.Children.Add(someInkPresenter);
现在 - 没有在持有_myCanvas的XAML的代码隐藏中构建InkPresenter我需要做这不同。我想做的是创建一个InkPresenter并将其添加到一个集合中:
public ObservableCollection< InkPresenter>图纸;
我现在的问题是如何将Canvas绑定到此ObservableCollection - 并将InkPresenters添加到收藏。我可以使用数据绑定来实现吗?
我想你可以用 ItemsControl + ItemsPanelTemplate 。像这样:
< ItemsControl ItemsSource ={Binding YourCollection}>
< ItemsControl.ItemsPanel>
< ItemsPanelTemplate>
< Canvas />
< / ItemsPanelTemplate>
< /ItemsControl.ItemsPanel>
< / ItemsControl>
要了解有关此方法的更多信息,请参阅Dr.WPF: ItemsControl:A到Z ( P是面板)
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..
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);
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;
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?
I think you can do this with ItemsControl + ItemsPanelTemplate. Like this:
<ItemsControl ItemsSource="{Binding YourCollection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
To read more about this approach refer to Dr.WPF: ItemsControl: A to Z (P is for Panel)
这篇关于将WPF画布儿童绑定到ObservableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!