我需要用可点击的基于按钮的单元格填充面板,如下所示:
这是用矩形完成的:
<ItemsControl ItemsSource="{Binding Path=Cells}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle>
<Rectangle.Fill>
<SolidColorBrush Color="Red"></SolidColorBrush>
</Rectangle.Fill>
</Rectangle>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<commonControls:UniformGrid ElementsGap="5" HorizontalCount="{Binding Path=CellsInRow}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
但我需要用按钮来做。我正在尝试:
<ItemsControl ItemsSource="{Binding Path=Cells}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button>
<Button.Background>
<SolidColorBrush Color="Red"></SolidColorBrush>
</Button.Background>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<commonControls:UniformGrid ElementsGap="5" HorizontalCount="{Binding Path=CellsInRow}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
但看起来是这样的:
我如何使用按钮从第一张图像中处理单元格?
UniformGrid 代码如下:
public class UniformGrid : Panel
{
public static readonly DependencyProperty HorizontalCountProperty =
DependencyProperty.Register("HorizontalCount", typeof (int), typeof (UniformGrid),
new PropertyMetadata(default(int)));
public int HorizontalCount
{
get { return (int) GetValue(HorizontalCountProperty); }
set { SetValue(HorizontalCountProperty, value); }
}
public static readonly DependencyProperty ElementsGapProperty =
DependencyProperty.Register("ElementsGap", typeof (double), typeof (UniformGrid),
new PropertyMetadata(default(double)));
public double ElementsGap
{
get { return (double) GetValue(ElementsGapProperty); }
set { SetValue(ElementsGapProperty, value); }
}
protected override Size MeasureOverride(Size availableSize)
{
return new Size();
}
protected override Size ArrangeOverride(Size finalSize)
{
if (Children != null && Children.Count != 0)
{
var squareSideForElement = (finalSize.Width - (HorizontalCount - 1)*ElementsGap)/HorizontalCount;
var sizeOfElement = new Size(squareSideForElement, squareSideForElement);
for (var i = 0; i < Children.Count; i++)
{
var rowIndex = i%HorizontalCount;
var columnIndex = i/HorizontalCount;
var resultPoint = new Point
{
X = rowIndex*(squareSideForElement + ElementsGap),
Y = columnIndex*(squareSideForElement + ElementsGap)
};
Children[i].Arrange(new Rect(resultPoint, sizeOfElement));
}
}
return finalSize;
}
}