Saturday, July 25, 2015

Minimum column width in WPF ListView/GridView

It seems that it is not possible to set the minimum width of a column within XAML. But it can be forced withn code-behind. Laurent Bugnion has found the solution (http://geekswithblogs.net/lbugnion/archive/2008/05/06/wpf-listviewgridview-minimum-and-maximum-width-for-a-column.aspx).

The ListView is defined in the XAML part.
 
            <ListView x:Name="MyListView">
                <!-- ... -->
            <ListView.ContextMenu>

In the constructor of the code-behind part the event handler is added.
 
            ResultDataView.AddHandler(Thumb.DragDeltaEvent,
                new DragDeltaEventHandler(Thumb_DragDelta), true);

The event handler takes care that column width is not set under 20 (in this example).
 
        private void Thumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            Thumb senderAsThumb = e.OriginalSource as Thumb;
            GridViewColumnHeader header = senderAsThumb.TemplatedParent as
                                                            GridViewColumnHeader;
            if (header == null)
            {
                return;
            }
 
            if (header.Column.ActualWidth < 20)
            {
                header.Column.Width = 20;
            }
        }