【问题标题】:Creating a grid filled with rectangles创建一个填充有矩形的网格
【发布时间】:2014-07-28 21:32:31
【问题描述】:

我想做这样的事情

我可以通过使用以下代码将矩形硬编码到网格中来做到这一点:

<Rectangle Grid.Column="0" Grid.Row="0" Fill="Black" />
<Rectangle Grid.Column="1" Grid.Row="0" Fill="Black" />
<Rectangle Grid.Column="2" Grid.Row="0" Fill="Black" />
<Rectangle Grid.Column="3" Grid.Row="0" Fill="Black" />
<Rectangle Grid.Column="4" Grid.Row="0" Fill="Black" />

然而,这只是一条线,如果我需要不同的尺寸,它会变得非常混乱。有没有更简单的方法来实现这一点,同时仍然能够向每个矩形添加事件?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    将运行时可变数量的项目绑定到网格有点棘手。一种选择是使用ItemsControl,将Grid 用作ItemsPanel

    您将在视图模型中拥有一个二维数组,每个单元格都包含其行号和列号。使用ItemContainerStyle 将容器的Grid.RowGrid.Column 附加属性绑定到单元格视图模型属性。

    <ItemsControl ItemsSource="{Binding Cells}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Grid />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="ContentPresenter">
                <Setter Property="Grid.Row" Value="{Binding RowNumber}" />
                <Setter Property="Grid.Column" Value="{Binding ColumnNumber}" />
            </Style>
        </ItemsControl.ItemContainerStyle>
    
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Rectangle Fill="Black" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    
    </ItemsControl>
    

    上面需要添加的部分是将行/列定义添加到网格中。为此,我将使用 attached properties 为您添加这些定义,允许您将定义绑定到视图模型中的属性。这样,您可以编写如下内容:

            <ItemsPanelTemplate>
                <Grid GridHelpers.RowCount="{Binding RowCount}" 
                      GridHelpers.ColumnCount="{Binding ColumnCount}" />
            </ItemsPanelTemplate>
    

    最后,对于事件,您可以使用EventTriggerInvokeCommandAction 在矩形的任何事件上触发ICommand

            <DataTemplate>
                <Rectangle>
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="MouseDoubleClick">
                            <i:InvokeCommandAction Command="{Binding RectangleClickCommand}"
                                                   CommandParameter="{Binding}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </Rectangle>
            </DataTemplate>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      相关资源
      最近更新 更多