hammil
hammil

Reputation: 149

Giving grid columns a minimum width while next to a shared size group

I'm using a Grid-based ItemsControl to display a bunch of properties. When the available space is too small, the control is rendered like this:

Problem

The DataTemplate for each item uses a Grid with a SharedSizeGroup for the labels. What I'd like is for the input box to be given a minimum width, say 50px, reducing the label width if necessary. When I tried just setting MinWidth, the box would just render outside of the grid - like the SharedSizeGroup column was always being given a higher priority.

Here's the relevant XAML; the default template for each item...

<DataTemplate DataType="{x:Type local:ViewModel+PropertyWrapper}">
    <Grid Margin="2">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" SharedSizeGroup="Key"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" x:Name="PLabel" Text="{Binding Name}" Margin="0,0,4,0"/>
        <TextBox Grid.Column="1" Text="{Binding Value}"/>
    </Grid>
</DataTemplate>

... and the code used to generate the list

<ItemsControl x:Key="PropertyListNoFill" x:Shared="False" Margin="0,3,0,0" Background="{x:Null}" BorderBrush="{x:Null}"
                ItemsSource="{Binding}"
                Grid.IsSharedSizeScope="True"
                HorizontalContentAlignment="Stretch"
                ItemTemplateSelector="{StaticResource PropertyTemplateSelector}" >
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <DockPanel LastChildFill="False" IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style>
            <Setter Property="DockPanel.Dock" Value="Top"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>

Upvotes: 2

Views: 300

Answers (1)

Funk
Funk

Reputation: 11211

Try it the other way around.

Instead of setting a MinWidth on the second column, put a MaxWidth on the first.

Using a Converter

public class WidthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double gridWidth = (double)value;
        return gridWidth - 50;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Inside the DataTemplate

<Grid.ColumnDefinitions>
    <ColumnDefinition 
        SharedSizeGroup="Key" 
        MaxWidth="{Binding ActualWidth, 
                           RelativeSource={RelativeSource AncestorType={x:Type Grid}}, 
                           Converter={StaticResource WidthConverter}}"/>
    <ColumnDefinition />
</Grid.ColumnDefinitions>

Upvotes: 1

Related Questions