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

时光怂恿深爱的人放手 提交于 2019-11-28 08:04:20
Tomas Grosup

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.

Anon

Set Width = "Auto" in XAML.

Then in the code:

MinWidth = ActualWidth
Width = new GridLength(1, GridUnitType.Star)

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.

danielcooperxyz

Give the column a name in the XAML:

<Grid>
      <Grid.ColumnDefinitions>
             <ColumnDefinition Width="*" Name="Col1"/>
             <ColumnDefinition Width="*"/>
      </Grid.ColumnDefinitions>
</Grid>

Then set the MinWidth property in the code as shown below:

public MainWindow()
{
    InitializeComponent();

    Col1.MinWidth = 340; //enter desired minimum width here
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!