C# 绑定到画布
我的类中有一个canvas属性,我想知道是否可以将它绑定到xaml中的canvas 数据绑定在画布中如何工作C# 绑定到画布,c#,wpf,xaml,C#,Wpf,Xaml,我的类中有一个canvas属性,我想知道是否可以将它绑定到xaml中的canvas 数据绑定在画布中如何工作 <Canvas ItemSource="{Binding ClassCanvas}" /> 是 您可以绑定到画布或任何其他对象。如果希望在XAML中定义的画布将整个画布作为单个项包含在类中,您可以编写: <Canvas> <ContentPresenter Content="{Binding ClassCanvas}" /> ... oth
<Canvas ItemSource="{Binding ClassCanvas}" />
是
您可以绑定到画布或任何其他对象。如果希望在XAML中定义的画布将整个画布作为单个项包含在类中,您可以编写:
<Canvas>
<ContentPresenter Content="{Binding ClassCanvas}" />
... other items here ...
</Canvas>
... 这里的其他项目。。。
如果希望在XAML中定义的画布包含与在类中定义的画布相同的所有UIElement,这是不可能的,因为UIElement只能有一个UIElement父级。因此,如果类中定义的画布是给定UIElement的父元素,那么在XAML中定义的画布就不能是 如果希望画布显示类中定义的画布中每个UIElement的数据,可以使用带有画布面板和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>
... 使用VisualBrush或自定义显示在此处显示UIElement
请注意,此代码只扫描子属性一次,因为它不是INotifyCollectionChanged集合
如果要绑定到类中包含UIElements集合及其Canvas.Top和Canvas.Left属性集的属性,如果容器是ObservableCollection而不是Canvas,则可以轻松地执行此操作
Canvas类从未设计用于数据层。我强烈建议您切换到使用ObservableCollection,并且仅将画布作为视图的一部分使用。这样我就可以在类中拥有一个画布对象,并将其绑定到xaml中的画布?数据绑定将如何工作?我是否可以将子对象添加到类的画布中,而这将在xaml中发生变化?您可以在类上设置
canvas
对象以引用xaml中的画布。