【发布时间】:2020-03-30 18:32:09
【问题描述】:
我有一个看似简单的用例,但它困扰了我好几个小时
我有一个两行两列的网格,第一列应采用所有可用宽度,第二列应采用所需宽度。问题在于第二列的“所需宽度”。此列在顶行包含一个数据网格,在底行包含一个标签(为简单起见)。 数据网格有两列,它们都应占数据网格的 50% 宽度。
我想要:
- 如果标签比数据网格宽,则数据网格应按比例放大(数据网格末尾可能不会出现半列,填满剩余空间)
- 如果数据网格比标签宽,列可能不是 小于数据网格所需的大小。
问题:
- 如果我将数据网格列设置为占用所有可用空间(宽度='*'),如果标签大于数据网格(但如果标签更小,数据网格会缩小到标签的宽度,而不是所有文字都可读)
- 如果我将列设置为“自动调整大小”,它的工作原理是标签小于数据网格(但如果标签更大,则会出现“半”列(这真的很伤我的眼睛)。
代码:
x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid Grid.Column="1" Name="grid">
<!-- Change column width to simulate the problemn-->
<DataGrid ItemsSource="{Binding Items}" ColumnWidth="*" RowHeaderWidth="0" Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource AncestorType={x:Type Grid}}}"/>
</Grid>
<!-- change label text to simulate problemn-->
<Label Grid.Row="1" Grid.Column="1" Content="x"/>
</Grid>
- 绑定到网格的实际宽度是让列正确放大
- Items 是一个对象列表(包含两个字符串值)
【问题讨论】: