简体   繁体   中英

WPF set grid column width relative to auto-sized column width

How can I do the following:

<Window x:Class="MyClientsWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Login" WindowStartupLocation="CenterScreen"
    SizeToContent="WidthAndHeight" 
    MaxWidth="800" MaxHeight="600">

  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" Name="labelColumn"/>
      <ColumnDefinition Width="2*" Name="entryColumn"/>
    </Grid.ColumnDefinitions>

    <TextBlock Grid.Row="0" Text="First name: " Name="firstNameLabel"
               Margin="4" VerticalAlignment="Center"/>
    <TextBox Grid.Row="0" Grid.Column="1" 
             Margin="4" HorizontalAlignment="Stretch"  />
    <TextBlock Grid.Row="1" Text="Last name: " Name="lastNameLabel"
               Margin="4" VerticalAlignment="Center"/>
    <TextBox Grid.Row="1" Grid.Column="1" 
             Margin="4" HorizontalAlignment="Stretch"  />
  </Grid>

Second column width must be twice as of the first, but width of the first column is automatic, and depends on font family, font size etc. Also, second column needs to be stretched when window is resized.

I don't know whether it is best answer or not, but I have found 2 approaches:

1)

<ColumnDefinition Width="*" Name="entryColumn" MinWidth="{Binding 
                ElementName=firstNameLabel, Path=ActualWidth}, 
                Converter={StaticResource MultiplyByTwoConverter}"/>

2) In code-beihind, inside Window.Loaded event handler:

private void onLoaded(object sender, RoutedEventArgs e)
{
     entryColumn.MinWidth = labelColumn.ActualWidth * 2;
}

First also works in design mode, but second doesn't. The following works in design mode, but not at runtime:

<ColumnDefinition Width="*" Name="entryColumn" MinWidth="{Binding 
                ElementName=labelColumn, Path=ActualWidth}, 
                Converter={StaticResource MultiplyByTwoConverter}"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM