我在我的类中有一个canvas属性,我想知道是否可以将其绑定到xaml中的canvas?
在canvas中,数据绑定应该如何工作?
<Canvas ItemSource="{Binding ClassCanvas}" />
<Canvas>
<ContentPresenter Content="{Binding ClassCanvas}" />
... other items here ...
</Canvas>
如果你希望在XAML中定义的Canvas包含与类中定义的Canvas相同的UI元素,这是不可能的,因为一个UI元素只能有一个UI元素父级。所以如果类中定义的Canvas是给定UI元素的父级,那么XAML中定义的Canvas就无法成为其父级。
如果你想让Canvas显示来自类中定义的Canvas中每个UI元素的数据,你可以使用一个带有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>
可以。
你可以绑定到画布或任何其他对象。
Canvas
对象来引用 XAML 中的画布。 - SLaks