将集合绑定到网格

本文关键字:网格 绑定 集合 | 更新日期: 2023-09-27 18:22:06

我有一个名为Fly的对象,它具有属性Position(Point)和Orientation(double)。在MainViewModel中,我有一个名为Flies的自定义对象Fly的集合。

苍蝇的视图是.png图像。我想在MainWindow中将Flies绑定到我的Grid,使用它们的属性PositionOrientation在屏幕上显示苍蝇。

我以前从未做过这种合集的装订。我之前所做的是将集合绑定到ListBoxItemsControl:

        <ItemsControl ItemsSource="{Binding MyCollection}">
        <ItemsControl.Template>
            <ControlTemplate>
                <ScrollViewer>
                    <ItemsPresenter/>
                </ScrollViewer>
            </ControlTemplate>
        </ItemsControl.Template>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <local:ItemView/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

如何将对象绑定到网格或任何其他控件以显示正确的位置和角度方向?

将集合绑定到网格

首先,不应该设置ItemsControl.Template属性,除非实际上想为其定义一个新的ControlTemplate…用相同的ControlTemplate替换默认CCD_14当然没有意义。接下来,如果你的ItemView只是一个Image,那么它似乎毫无意义。。。只需使用Image即可。通过这种方式,您将能够正确地对属性进行数据绑定。

有几种方法可以满足您的需求,但您可以使用RotateTransform作为Orientation,也可以使用CCD20来移动项目。试试这样的东西:

<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>

基于问题中的一些假设,这里是您正在寻找的

<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>

我做了什么

  • 将Canvas设置为ItemsControl的ItemsPanel,该控件将承载项目(flies)
  • 创建了一个以ContentPresenter为目标的样式,该样式是ContentPresenter中项目的默认宿主
  • 装订画布。左&画布。顶部到相应位置的X&Y
  • 为方向添加了RotateTransform,并将角度绑定到orientation属性

我可以假设苍蝇应该飞,所以在这种情况下,你可能想要改变X&Y将改变飞行位置。但由于Point类不会通知子属性的更改,因此绑定可能无法按预期工作。因此,作为一个建议,您可能希望创建自己的Point类,其中包含属性更改通知。