我想做这样的事情
我可以通过使用以下代码将矩形硬编码到网格中来实现:
<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" />
Run Code Online (Sandbox Code Playgroud)
然而,这只是一行,如果我需要不同的尺寸,它可能会变得非常混乱.有没有更简单的方法来实现这一点,同时仍然能够向每个矩形添加事件?
将运行时可变数量的项目绑定到网格有点棘手。一种选择是使用 an ItemsControl
,其中 aGrid
作为ItemsPanel
。
视图模型中将有一个二维数组,每个单元格都包含其行号和列号。使用 将ItemContainerStyle
容器的属性Grid.Row
和Grid.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>
Run Code Online (Sandbox Code Playgroud)
需要添加到上面的部分是将行/列定义添加到网格中。为此,我将使用附加属性为您添加这些定义,从而允许您将定义绑定到视图模型中的属性。这样,您就可以编写如下内容:
<ItemsPanelTemplate>
<Grid GridHelpers.RowCount="{Binding RowCount}"
GridHelpers.ColumnCount="{Binding ColumnCount}" />
</ItemsPanelTemplate>
Run Code Online (Sandbox Code Playgroud)
最后,对于事件,您可以使用 anEventTrigger
和 anInvokeCommandAction
来触发ICommand
矩形的任何事件。
<DataTemplate>
<Rectangle>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding RectangleClickCommand}"
CommandParameter="{Binding}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Rectangle>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
980 次 |
最近记录: |