Binding WPF Canvas Children to an ObservableCollection

不羁岁月 提交于 2019-12-17 15:57:17

问题


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?


回答1:


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)




回答2:


The solution Anvaka suggested is great, but as John Bowen pointed out you need to know a bit more, if you would like to actually bind your items to the Canvas attached properties.

Here's an example on how to bind to Canvas.Left and Canvas.Top:

<ItemsControl ItemsSource="{Binding YourCollection}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <Canvas />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
    <Style TargetType="ContentPresenter">
        <Setter Property="Canvas.Left" Value="{Binding YourModelLeft}" />
        <Setter Property="Canvas.Top" Value="{Binding YourModelTop}" />
    </Style>
</ItemsControl.ItemContainerStyle>

Btw, I found the solution on this question, after I tried Anvaka's suggestion, where the binding didn't work.

Hopefully this helps others, looking for the same answer.



来源:https://stackoverflow.com/questions/2317713/binding-wpf-canvas-children-to-an-observablecollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!