绑定到画布 [英] Binding to Canvas
问题描述
我的课堂上有一个canvas属性,我想知道是否可以将它绑定到xaml中的画布上吗?
I have a canvas property in my class and I was wondering if it's possible to bind that to a canvas in xaml?
数据绑定如何在画布中工作?
How would the databinding work in the canvas?
<Canvas ItemSource="{Binding ClassCanvas}" />
推荐答案
如果您希望XAML中定义的Canvas包含您可以在班级中将整个Canvas作为单个项目编写:
If you want your Canvas defined in XAML to include the entire Canvas in your class as a single item you can write:
<Canvas>
<ContentPresenter Content="{Binding ClassCanvas}" />
... other items here ...
</Canvas>
如果您希望XAML中定义的Canvas包含与类中定义的Canvas相同的UIElements ,这是不可能的,因为一个UIElement只能有一个UIElement父对象。因此,如果类中定义的Canvas是给定UIElement的父级,则XAML中定义的Canvas不能为父。
If you want your Canvas defined in XAML to include all the same UIElements as the Canvas defined in your class, it is impossible because a UIElement can have only one UIElement parent. So if the Canvas defined in the class is the parent of a given UIElement, the Canvas defined in XAML can't be.
如果希望Canvas显示来自以下位置的数据您可以在类中定义Canvas中的每个UIElement时,都可以使用带有Canvas面板和DataTemplate的ItemsControl:
If you want your Canvas to display data from each UIElement in the Canvas defined in your class, you can do this with an ItemsControl with a Canvas panel and a DataTemplate:
<ItemsControl ItemsSource="{Binding ClassCanvas.Children}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl>
<ItemsControl.ItemsContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding (Canvas.Left)}" />
<Setter Property="Canvas.Left" Value="{Binding (Canvas.Top)}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
... display of UIElement here, either using VisualBrush or custom display
</ControlTemplate>
<Setter.Value>
</Setter>
</Style>
</ItemsControl.ItemsContainerStyle>
</ItemsControl>
请注意,由于此代码不是INotifyCollectionChanged集合,因此只会扫描Children属性一次。
Note that this code will only scan the Children property once since it is not an INotifyCollectionChanged collection.
如果您要绑定到包含UIElements集合且其Canvas.Top和Canvas.Left属性设置为类的属性,则如果容器是一个ObservableCollection而不是Canvas。
If you want to bind to a property in your class that contains a collection of UIElements with their Canvas.Top and Canvas.Left properties set, you can easily do this if the container is an ObservableCollection instead of a Canvas.
Canvas类从未设计用于数据层。我强烈建议您在该处切换到使用ObservableCollection,而仅将Canvas用作视图的一部分。
The Canvas class was never designed for use within your data layer. I would strongly recommend you switch to using an ObservableCollection there and only use Canvas as part of your view.
这篇关于绑定到画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!