我有一个对象的二维数组,基本上我想将每个对象绑定到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);
}
}
}
发布于 2009-10-28 17:19:50
您可能想要查看此链接:http://www.thinkbottomup.com.au/site/blog/Game_of_Life_in_XAML_WPF_using_embedded_Python
如果使用列表中的列表,则可以使用myListx访问单元格。
https://stackoverflow.com/questions/276808
复制相似问题