C# – WPF: Getting System.Windows.Data Error’s on changing rows in a grid

cwindowswpf

I have a grid that I dynamically need to resize in the number of columns based on the size of my window.

The only way I have found to make it work is using:

FrameworkElementFactory fGrid = new FrameworkElementFactory
  (typeof(System.Windows.Controls.Primitives.UniformGrid));

fGrid.SetValue(System.Windows.Controls.Primitives.UniformGrid.ColumnsProperty, columns);
listbox.ItemsPanel = new ItemsPanelTemplate(fGrid);

In my listbox_SizeChanged event handler. Sadly it gives out the following (harmless) errors. Any better ideas for how to change it dynamically?

System.Windows.Data Error: 4 : Cannot
find source for binding with reference
'RelativeSource FindAncestor,
AncestorType='System.Windows.Controls.ItemsControl',
AncestorLevel='1''.
BindingExpression:Path=HorizontalContentAlignment;
DataItem=null; target element is
'ListViewItem' (Name=''); target
property is
'HorizontalContentAlignment' (type
'HorizontalAlignment')

Best Answer

Data bind the UniformGrid.Columns property:

<ListBox>
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <UniformGrid Rows="10" Columns="{Binding ColumnCount}" />
    </ItemsPanelTemplate>
  </ListBox.ItemsPanel>
</ListBox>

Then update the ColumnCount in your SizeChanged handler.

This assumes you can define a ColumnCount on the ListBox's DataContext. If this is undesirable, you can easily place the column count in some other bindable place, for example defining an attached property on the ListBox, binding to that and setting the attached property's value in your SizeChanged handler. In any case, the key is to bind the Columns property rather than recreating the entire ItemsPanelTemplate in code.

Related Topic