Take the 2-minute tour ×

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

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')

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Data bind the UniformGrid.Columns property:

      <UniformGrid Rows="10" Columns="{Binding ColumnCount}" />

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.

share|improve this answer
add comment

Your Answer


