绑定WPF画布孩子一个ObservableCollection画布、绑定、孩子、ObservableCollection

2023-09-02 02:00:58 作者:4.月色如浅梦

在我的WPF应用程序我有一个画布中,我做了一些图纸。早些时候,我在处理后面的code中的绘图,但现在我已经分解所有的东西到视图模型。这给了我一些挑战。

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..

我拿着笔画数墨水presenter对象。 Earier我在code加他们为孩子们的画布背后 - 是这样的:

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); 

现在 - 而不是建立墨水presenter在XAML的code-背后持有_myCanvas我需要不同的方法来做这个。我想要做的是创造一个墨水presenter并将其添加到集合:

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;

我现在的问题是如何绑定画布到此的ObservableCollection - 并当加入到集合中的墨水presenters显示。我能做到这一点使用数据绑定不知何故?

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到Z ( P代表小组)

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