Álvaro García
Álvaro García

Reputation: 19396

How to adjust width of column to content?

I have a column in a datagrid which I am setting the width of the textblck with a multivalue converter. But the width of the column is not modified. I would like that the width column adjust to the content of the texblock.

The column is this:

            <DataGridTextColumn Header="Columna2" Binding="{Binding}" Width="AUTO">
                <DataGridTextColumn.ElementStyle>
                    <Style TargetType="{x:Type TextBlock}">
                        <Setter Property="HorizontalAlignment" Value="Left"/>
                        <Setter Property="Background" Value="Orange"/>
                        <Setter Property="Width">
                            <Setter.Value>
                                <MultiBinding Converter="{StaticResource MiMultiValueConverter}">
                                    <Binding Path="UseConverterIsChecked" Source="{StaticResource vm}"/>
                                    <Binding Path="WidthColumn2" Source="{StaticResource vm}"/>
                                </MultiBinding>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>

I know that the textblock is resize correctly because I set a background to see which is the real size of the textblock.

This is the original size:

enter image description here

And this is when the converter set the value of the textblock:

enter image description here

How could I adjust the size of the column?

Thanks.

EDIT:

If I use horizontal stretch as is advised in some comment, I get this result:

enter image description here

EDIT:

This is the code MiMultiValueConverter:

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    bool miBlUsarConverter = (bool)values[0];
    double miDbAncho = (double)values[1];

    return (miBlUsarConverter) ? miDbAncho : 200;
}

Upvotes: 0

Views: 74

Answers (1)

Shrimperator
Shrimperator

Reputation: 467

You're setting the width of the elements contained inside the DataGrid column, instead of the actual column. The proper way of resizing your column would be to set the width property of the DataGridTextColumn itself:

<DataGridTextColumn Header="Columna2" Binding="{Binding}" Width="1*">

In your case, you'll want to replace it with your binding from above.

For more information, here is the official doc: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/sizing-options-in-the-datagrid-control?view=netframeworkdesktop-4.8

Upvotes: 1

Related Questions