我的类中有一个 canvas 属性,我想知道是否可以将其绑定到 xaml 中的画布?
数据绑定在画布中如何工作?
<Canvas ItemSource="{Binding ClassCanvas}" />
如果您希望 XAML 中定义的 Canvas 将整个 Canvas 作为单个项目包含在类中,您可以编写:
<Canvas>
<ContentPresenter Content="{Binding ClassCanvas}" />
... other items here ...
</Canvas>
如果您希望 XAML 中定义的 Canvas 包含与类中定义的 Canvas 相同的所有 UIElement,这是不可能的,因为 UIElement 只能有一个 UIElement 父级。因此,如果类中定义的 Canvas 是给定 UIElement 的父级,则 XAML 中定义的 Canvas 不能是。
如果您希望 Canvas 显示类中定义的 Canvas 中每个 UIElement 的数据,您可以使用带有 Canvas 面板和 DataTemplate 的 ItemsControl 来完成此操作:
<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>
请注意,此代码只会扫描 Children 属性一次,因为它不是 INotifyCollectionChanged 集合。
如果您想要绑定到类中包含 UIElements 集合并设置了 Canvas.Top 和 Canvas.Left 属性的属性,如果容器是 ObservableCollection 而不是 Canvas,则可以轻松执行此操作。
Canvas 类从来就不是为在数据层中使用而设计的。我强烈建议您改用 ObservableCollection 并仅使用 Canvas 作为视图的一部分。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)