GridViewColumn.Width binding and double-click to autosize column

2k Views Asked by At

Binding column width like this

<ListView ...>
    <ListView.View>
        <GridView>
            <GridViewColumn Width="{Binding Width, Mode=TwoWay}" ... />
            ... more columns
        </GridView>
    </ListView.View>
</ListView>

The problem: when double clicking column header line (to autosize column) no Width setter is triggered, which means binding source is not updated after such column width changing. Normal column resizing works without problems.

Suggestions?

I don't want to prevent double-click autosizing, only to fix an issue.

3

There are 3 best solutions below

2
On BEST ANSWER

Looking at the double click handler source code, it looks like the Width property should be updated. Perhaps something is going wrong in the binding? You might want to make your binding verbose and see what prints in the output window.

That issue aside, you may not get the behavior you desire by binding to the Width property. As you can tell from the double click handler, it gets set to NaN to make the column automatically resize. This means that even if your property setter gets called, it is going to get NaN passed to it. You could bind to ActualWidth using a OneWayToSource binding mode, unless you actually need the binding to be TwoWay for other reasons.

0
On

I'd prefer to delete my question, but perhaps it will be usefull (I doubt) to someone else doing same mistake.

Problem was with Width type. I used int and it seems to works flawlessly. But it doesn't work with double-click resizing for whatever reasons.

To fix: use double Width {get; set;} to bind to, not int.

0
On

In my case I've solved the question doing this:

1. I have a property "_gridView" which is the GridView object representing the view of a ListView whose name is "_listView".

<ListView x:Name="_listView">
    <ListView.View>
        <GridView x:Name="_gridView">
            <GridViewColumn Header="Whatever"/>
        </GridView >
    </ListView.View>
</ListView>

2. I haved added this other piece of code to updated the width of the columns of the GridView. This is based on this .NET reference of GridViewColumnHeader.

private void UpdateWidths()
{
    foreach (var column in this._gridView.Columns)
    {
        column.Width = column.ActualWidth;
        column.Width = Double.NaN;
    }
}

3. And in the constructor of the WPF window, I've inserted this other code to execute the update of the widths each time the "ItemsSource" of "_listView" changes.:

public MainWindow()
{
    InitializeComponent();

    DependencyPropertyDescriptor
        .FromProperty(ListView.ItemsSourceProperty, typeof(ListView))
        .AddValueChanged(_listView, (s, e) => {
            UpdateWidths();
    });
}

4. Therefore, each time I change the "ItemsSource" property of the object "_listView" all the columns are updated.

_listView.ItemsSource = __New value__