繁体   English   中英

WPF设置网格列宽相对于自动调整的列宽

[英]WPF set grid column width relative to auto-sized column width

如何执行以下操作:

<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>

第二列的宽度必须是第一列的两倍,但是第一列的宽度是自动的,并且取决于字体系列,字体大小等。此外,调整窗口大小时,第二列需要进行拉伸。

我不知道这是否是最佳答案,但是我发现了两种方法:

1)

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

2)在隐藏代码中,在Window.Loaded事件处理程序内部:

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

第一个也可以在设计模式下工作,但第二个则不能。 以下内容在设计模式下有效,但在运行时无效:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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