How apply MinWidth for ListView columns in WPF in control template?
Asked Answered
B

7

7

Following the answer to a similar question here, I was able to set the MinWidth on the XAML page.

What I would like to do is accomplish this in the control template for all GridViewColumn's in all ListView's.

Is this possible?

Update:

I tried a simple bit of sample code below, but it does not work:

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Window.Resources>
        <Style TargetType="{x:Type GridViewColumnHeader}" >
            <Setter Property="MinWidth" Value="200" />
        </Style>
    </Window.Resources>

    <Grid Width="500">
        <Border BorderBrush="Black" BorderThickness="2" Margin="20">
            <ListView SelectionMode="Single">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="Header 1" Width="Auto">
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <TextBlock Text="Hello There"/>
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                        <GridViewColumn Header="Header 2" Width="Auto" />
                    </GridView>
                </ListView.View>
            </ListView>
        </Border>
    </Grid>
</Window>
Bracey answered 10/4, 2012 at 22:50 Comment(2)
GridViewColumn does not even have a MinWidth property. You can't can't set a Property in a style or control template that does not exists. Please post your XAML for how you set a MinWidth on a GridViewColumn.Ankylose
In the link, it demonstrates the use of the Thumb and handling the DragDelta event to accomplish the MinWidth. Is there a way to accomplish this in a control template?Bracey
I
10

If you use a GridViewColumnHeader you can handle size changes:

  <GridView>
     <GridViewColumn>
        <GridViewColumnHeader Content="HeaderContent" SizeChanged="HandleColumnHeaderSizeChanged"/> 
   ...

in Code:

    private void HandleColumnHeaderSizeChanged(object sender, SizeChangedEventArgs sizeChangedEventArgs)
    {
        if (sizeChangedEventArgs.NewSize.Width <= 60) {
            sizeChangedEventArgs.Handled = true;
            ((GridViewColumnHeader) sender).Column.Width = 60;
        }
    }
Irritable answered 11/12, 2014 at 11:0 Comment(1)
Thanks. I ended up making an attached property for this so I can use as: gv:MinWdth="75". I wish this came out of the box however.Bedmate
M
4
 <ListView>
        <ListView.View>
            <GridView>
                <GridViewColumn>
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock MinWidth="100"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                 ...more columns...
            </GridView>
        </ListView.View>
    </ListView>
Mikkimiko answered 10/4, 2012 at 23:13 Comment(1)
I was actually looking for such a solution. It works great when you need to apply it to a specific column. I only had to add the binding on the textblock.Quartered
A
4
<Window.Resources>
    <Style TargetType="{x:Type GridViewColumnHeader}" >
        <Setter Property="MinWidth" Value="400" />
    </Style>
</Window.Resources>
Ankylose answered 11/4, 2012 at 0:11 Comment(9)
I tried this, but did not work. Didn't you say that GridViewColumn does not have a MinWidth?Bracey
Read - GridViewColumnHeader - not GridViewColumn. I tested this - it works.Ankylose
I posted a sample, which is not working for me. Could you please see if there is something else you may be doing that I do not have?Bracey
Please try taking width = auto off the individual columns. I really did test this and it worked in my GridView.Ankylose
Same result, dragging/sizing the column bar goes crazy, not smooth, jumps around and does not hold the MinWidth. If it is working for you something must be different. Could you try running my example?Bracey
Dude I tested YOUR code and it does apply a minimum. Yes bad stuff happens when you re-size but you have Grid width of 400 and with the margin there is not room for two 200. Even without a min the "Hello There" does not show up as you are not really binding. I answered and fixed the stated question.Ankylose
You have a point on the 400 width, oversight on my end. But, regardless it is still not working for me. You don't need to get uptight about it. I would accept the answer if it worked also for me. Unfortunately, the code sample is not working on my end and I am still seeking to resolve this.Bracey
Doesn't work for me, tried placing it in my Stylesheet, in my Window, in the actual control - nothing...Plaster
I can only agree with @Bracey - the columns appear to initialize correctly with minWidth, but then go completely nuts when resizing. This is not the solution.Collaborate
O
4

I stumbled into this one also. To solved it I had to do two things :

  1. Modify the ControlTemplate of ListView's header.
  2. Handle the DragDelta event of the Thumb inside the ControlTemplate.

ListView's header is GridViewColumnHeader. Shown below is a simplified version of GridViewColumnHeader's ControlTemplate. As we can see, it uses a Thumb in a Canvas to create the drag/resize effect.

PS: To obtain the complete GridViewColumnHeader ControlTemplate please refer to How to grab WPF 4.0 control default templates?

<ControlTemplate TargetType="GridViewColumnHeader">
<Grid SnapsToDevicePixels="True">
    <Border BorderThickness="0,1,0,1" Name="HeaderBorder" ...>
    <!-- omitted -->
    </Border>
    <Border BorderThickness="1,0,1,1" Name="HeaderHoverBorder" Margin="1,1,0,0" />
    <Border BorderThickness="1,1,1,0" Name="HeaderPressBorder" Margin="1,0,0,1" />
    <Canvas>
        <Thumb Name="PART_HeaderGripper">
        <!-- omitted -->
        </Thumb>
    </Canvas>
</Grid>
<ControlTemplate.Triggers>
<!-- omitted -->
</ControlTemplate.Triggers>

So In order to limit the size of GridViewColumnHeader, we need to hook Thumb's drag events(DragStarted, DragDelta, DragCompleted...etc).

Turned out all we need is the DragDelta event as long we can know the MinSize within the DragDeltaEventHandler.

Shown below is modified XAML with comment.

<Grid Width="500">
    <Border BorderBrush="Black" BorderThickness="2" Margin="20">
        <ListView SelectionMode="Single">
            <ListView.View>
                <GridView>                        
                    <GridViewColumn Header="Header 1" Width="Auto">
                        <!-- Apply a style targeting GridViewColumnHeader with MinWidth = 80 and a ControlTemplate -->
                        <GridViewColumn.HeaderContainerStyle>
                            <Style TargetType="{x:Type GridViewColumnHeader}">
                                <Setter Property="MinWidth" Value="80" />
                                <Setter Property="Control.Template" Value="{DynamicResource myGridViewColumnHeaderControlTemplate}" />
                            </Style>
                        </GridViewColumn.HeaderContainerStyle>**
                    </GridViewColumn>
                    <GridViewColumn Header="Header 2" Width="Auto" />
                </GridView>
            </ListView.View>
        </ListView>
    </Border>
</Grid>

In the myGridViewColumnHeaderControlTemplate add some XAML to:

  1. Bind GridViewColumnHeader's MinWidth to Canvas's MinWidth.
  2. Hook up Thumb's DragDelta event.
<ControlTemplate x:Key="TemplateGridViewColumnHeader" TargetType="GridViewColumnHeader">
    <!-- omitted -->
    <Canvas MinWidth="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=MinWidth, Mode=OneTime}">
        <Thumb x:Name="PART_HeaderGripper" DragDelta="myGridViewColumnHeader_DragDelta">

Finally the myGridViewColumnHeader_DragDelta function:

    private void myGridViewColumnHeader_DragDelta(object sender, DragDeltaEventArgs e)
    {
        DependencyObject parent = sender as DependencyObject;

        try
        {
            do
            {
                parent = VisualTreeHelper.GetParent(parent as DependencyObject);
            } while (parent.GetType() != typeof(Canvas));

            Canvas canvas = parent as Canvas;
            if (canvas.ActualWidth + e.HorizontalChange < canvas.MinWidth)
            {
                e.Handled = true;
            }
        }
        catch
        {
        }
    }

This is the only way i find working. Do hope there is a simpler way.

Orellana answered 2/10, 2013 at 20:47 Comment(1)
Massive overkil imo.Bedmate
P
3

Update to the solution of Billy Jake O'Connor who gave the most simple, easy to implement and WORKING CORRECTLY solution of them all.

For the people who don't want all columns to share the same minimum width, with the next code update you can set specific minimum width for each column separately specifying the min width directly in the column properties.

public static class GridColumn {
    public static readonly DependencyProperty MinWidthProperty =
        DependencyProperty.RegisterAttached("MinWidth", typeof(double), typeof(GridColumn), new PropertyMetadata(75d, (s, e) => {
            if(s is GridViewColumn gridColumn ) {
                SetMinWidth(gridColumn);
                ((System.ComponentModel.INotifyPropertyChanged)gridColumn).PropertyChanged += (cs, ce) => {
                    if(ce.PropertyName == nameof(GridViewColumn.ActualWidth)) {
                        SetMinWidth(gridColumn);
                    }
                };
            }
        }));

    private static void SetMinWidth(GridViewColumn column) {
        double minWidth = (double)column.GetValue(MinWidthProperty);

        if(column.Width < minWidth)
            column.Width = minWidth;
    }

    public static double GetMinWidth(DependencyObject obj) => (double)obj.GetValue(MinWidthProperty);

    public static void SetMinWidth(DependencyObject obj, double value) => obj.SetValue(MinWidthProperty, value);
}

And the XAML could be something like this ("local" is your using namespace name, modify accordingly)

<ListView>
    <ListView.View>
        <GridView>
            <GridViewColumn local:GridColumn.MinWidth="25" />
            <GridViewColumn local:GridColumn.MinWidth="100" />
            <GridViewColumn local:GridColumn.MinWidth="200" />
        </GridView>
    </ListView.View>
</ListView>
Piquet answered 28/4, 2020 at 7:59 Comment(0)
R
2

I wanted to apply a minwidth to all columns, so I wrote this:

  public static class GridViewConstraints
  {
    public static readonly DependencyProperty MinColumnWidthProperty =
        DependencyProperty.RegisterAttached("MinColumnWidth", typeof(double), typeof(GridViewConstraints), new PropertyMetadata(75d, (s,e) =>
        {
            if(s is ListView listView)
            {
                listView.Loaded += (lvs, lve) =>
                {
                    if(listView.View is GridView view)
                    {
                        foreach (var column in view.Columns)
                        {
                            SetMinWidth(listView, column);

                            ((System.ComponentModel.INotifyPropertyChanged)column).PropertyChanged += (cs, ce) =>
                            {
                                if (ce.PropertyName == nameof(GridViewColumn.ActualWidth))
                                    SetMinWidth(listView, column);
                            };
                        }
                    }
                };
            }
        }));

    private static void SetMinWidth(ListView listView, GridViewColumn column)
    {
        double minWidth = (double)listView.GetValue(MinColumnWidthProperty);

        if (column.Width < minWidth)
            column.Width = minWidth;
    }

    public static double GetMinColumnWidth(DependencyObject obj) => (double)obj.GetValue(MinColumnWidthProperty);

    public static void SetMinColumnWidth(DependencyObject obj, double value) => obj.SetValue(MinColumnWidthProperty, value);
}

Just drop it on your listview:

<ListView b:GridViewConstraints.MinColumnWidth="255" />
Ramillies answered 19/7, 2018 at 11:37 Comment(2)
If you wanted this as a default, you could create a listview style that sets this value in setter. Hope this helps.Bedmate
I tried the other answers, including the style setter, and nothing worked properly. This one works perfect, great solution.Collaborate
F
0

You can try this, for each column, if you want to set different minimum width for all columns and maximum to auto

 <ListView.View>
    <GridView >
        <GridViewColumn Header="FILE NAME" DisplayMemberBinding="{Binding fileName}" Width="auto" >
            <GridViewColumn.HeaderContainerStyle>
                <Style TargetType="{x:Type GridViewColumnHeader}">
                    <Setter Property="MinWidth" Value="200" />

                </Style>
            </GridViewColumn.HeaderContainerStyle>
        </GridViewColumn>
                <GridViewColumn Header="ERROR DETAILS" DisplayMemberBinding="{Binding errorMessage}" Width="auto">
            <GridViewColumn.HeaderContainerStyle>
                <Style TargetType="{x:Type GridViewColumnHeader}">
                    <Setter Property="MinWidth" Value="396" />

                </Style>
            </GridViewColumn.HeaderContainerStyle>
        </GridViewColumn>

    </GridView>
</ListView.View>
Fley answered 3/5, 2021 at 6:47 Comment(1)
It doesn't work, the content overflows and is invisible.Kristlekristo

© 2022 - 2024 — McMap. All rights reserved.