C# 将集合绑定到网格
我有一个名为C# 将集合绑定到网格,c#,wpf,collections,C#,Wpf,Collections,我有一个名为Fly的对象,它的属性是Position(点)和Orientation(双)。 在我的MainViewModel中,我有一个自定义对象Fly的集合,称为Flies 苍蝇的视图是一个.png图像。我想使用苍蝇的属性Position和Orientation将苍蝇绑定到主窗口中的我的Grid,以在屏幕上显示苍蝇 我以前从未做过这样的收藏装订。我之前做的是将集合绑定到列表框或项控件: <ItemsControl ItemsSource="{Binding MyColle
Fly
的对象,它的属性是Position
(点)和Orientation
(双)。
在我的MainViewModel中,我有一个自定义对象Fly
的集合,称为Flies
苍蝇的视图是一个.png图像。我想使用苍蝇的属性Position
和Orientation
将苍蝇绑定到主窗口中的我的Grid
,以在屏幕上显示苍蝇
我以前从未做过这样的收藏装订。我之前做的是将集合绑定到列表框
或项控件
:
<ItemsControl ItemsSource="{Binding MyCollection}">
<ItemsControl.Template>
<ControlTemplate>
<ScrollViewer>
<ItemsPresenter/>
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:ItemView/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
如何将对象绑定到网格或任何其他控件以显示正确的位置和角度方向?基于以下问题中的一些假设,这就是您要寻找的
<ItemsControl ItemsSource="{Binding MyCollection}">
<ItemsControl.Resources>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left"
Value="{Binding Position.X}" />
<Setter Property="Canvas.Top"
Value="{Binding Position.Y}" />
<Setter Property="RenderTransform">
<Setter.Value>
<RotateTransform Angle="{Binding Orientation}" />
</Setter.Value>
</Setter>
</Style>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:ItemView />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我所做的
- 将画布设置为ItemsControl的ItemsPanel,该控件将承载项目(flies)
- 创建了以ContentPresenter为目标的样式,该样式是ContentPresenter中项目的默认宿主
- 绑定画布。左和画布。顶部到各自位置的X和Y
- 为方向添加了RotateTransform,并绑定了“角度到方向”属性
ItemsControl.Template
属性,除非您确实要为其定义新的ControlTemplate
。。。用相同的模板替换默认的ControlTemplate
显然没有意义。接下来,如果您的ItemView
只是一个图像,那么它似乎毫无意义。。。只需使用图像
。通过这种方式,您将能够正确地对属性进行数据绑定
有几种方法可以满足您的需求,但您可以使用旋转变换器
进行定位
,也可以使用旋转变换器
移动项目。试着这样做:
<ItemsControl ItemsSource="{Binding MyCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="/Images/Fly.png">
<Image.RenderTransform>
<TransformGroup>
<RotateTransform Angle="{Binding Orientation}" />
<TranslateTransform X="{Binding Position.X}"
Y="{Binding Position.Y}" />
</TransformGroup>
</Image.RenderTransform>
</Image>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>