Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to populate a WPF grid based on a 2-dimensional array
    primarykey
    data
    text
    <p>I have a 2-dimensional array of objects and I basically want to databind each one to a cell in a WPF grid. Currently I have this working but I am doing most of it procedurally. I create the correct number of row and column definitions, then I loop through the cells and create the controls and set up the correct bindings for each one. </p> <p>At a minimum I would like to be able to use a template to specify the controls and bindings in xaml. Ideally I would like to get rid of the procedural code and just do it all with databinding, but I'm not sure that's possible.</p> <p>Here is the code I am currently using:</p> <pre><code>public void BindGrid() { m_Grid.Children.Clear(); m_Grid.ColumnDefinitions.Clear(); m_Grid.RowDefinitions.Clear(); for (int x = 0; x &lt; MefGrid.Width; x++) { m_Grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star), }); } for (int y = 0; y &lt; MefGrid.Height; y++) { m_Grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star), }); } for (int x = 0; x &lt; MefGrid.Width; x++) { for (int y = 0; y &lt; 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); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload