如何基于二维数组填充WPF网格
我有一个二维的对象数组,我基本上想要将每个对象数据绑定到WPF网格中的单元格。目前我有这个工作,但我在程序上做了大部分工作。我创建了正确数量的行和列定义,然后循环遍历单元格并创建控件并为每个控件设置正确的绑定。
至少我希望能够使用模板来指定xaml中的控件和绑定。理想情况下,我想摆脱程序代码,并使用数据绑定完成所有操作,但我不确定这是否可能。
这是我目前使用的代码:
public void BindGrid(){
m_Grid.Children.Clear();
m_Grid.ColumnDefinitions.Clear();
m_Grid.RowDefinitions.Clear();
for (int x = 0; x < MefGrid.Width; x++)
{
m_Grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star), });
}
for (int y = 0; y < MefGrid.Height; y++)
{
m_Grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star), });
}
for (int x = 0; x < MefGrid.Width; x++)
{
for (int y = 0; y < MefGrid.Height; y++)
{
Cell cell = (Cell)MefGrid[x, y];
SolidColorBrush brush = new SolidColorBrush();
var binding = new Binding("On");
binding.Converter = new BoolColorConverter();
binding.Mode = BindingMode.OneWay;
BindingOperations.SetBinding(brush, SolidColorBrush.ColorProperty, binding);
var rect = new Rectangle();
rect.DataContext = cell;
rect.Fill = brush;
rect.SetValue(Grid.RowProperty, y);
rect.SetValue(Grid.ColumnProperty, x);
m_Grid.Children.Add(rect);
}
}}
精慕HU
慕容3067478
繁花不似锦
皈依舞
随时随地看视频慕课网APP