Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - DataGrid Column with Width="*", but MinWidth to Fit Contents

What would be the best/right way to have a set of DataGrid columns have proportional width (Width="\*"), but to have their minimum width be at least the width of their content? At the moment, if I use Width="*", then the columns stay exactly proportional, but content gets cropped if the columns get too thin. If I use Width="Auto", then the columns size themselves perfectly to their content, but this makes them all different sizes.

What I want is really a combination of the two, like Width="\*", MinWidth="Auto" so that when there's extra width the columns will all space out to equal widths, but when the grid is made smaller, the content never gets cropped.

Sadly, MinWidth="Auto" doesn't exist, so I guess I need to bind the column's MinWidth property, but it's hard to figure out exactly what I would bind it to.

How do I tell WPF "MinWidth=" the width of the column's widest piece of content?

like image 820
Andy T Avatar asked Aug 04 '10 09:08

Andy T


3 Answers

I know its a bit late, but I found your question and programmed a pure-XAML solution.

 <ColumnDefinition Width="42*" MinWidth="{Binding Path=ActualWidth, ElementName=projectInfoHeader }"/> 

Where the ElementName points to the control taking up most of the space. Of course thats only possible to do with elements, that do have a limited width. If you do it for example for a GroupBox, than you can resize only to larger width and never resize to smaller one.

If you have several candidates for the value of MinWidth, you need to write yourself a IMultiValueConverter, which takes an object[], parses it to floats, and returns the maximum (its just 1 linq query if you use it only yourselves and don't need to handle bad usage of the converter)

This way also supports dynamic changing of the MinWidth.

like image 144
Tomas Grosup Avatar answered Nov 16 '22 06:11

Tomas Grosup


Set Width = "Auto" in XAML.

Then in the code:

MinWidth = ActualWidth
Width = new GridLength(1, GridUnitType.Star)
like image 37
Anon Avatar answered Nov 16 '22 07:11

Anon


I also had problems to size Grid columns correctly inside the GridViewColumn. There were several things that I tried but then I found the UniformGrid. It was the ultimate solution for me. It just works. I haven't knew it before...seems that it doesn't exist in VS toolbox by default (?) and thus didn't know it even exists.

You can find more about UniformGrid from here.

like image 2
Ollikat Avatar answered Nov 16 '22 06:11

Ollikat