[英]WPF datagrid MinWidth=auto MaxWidth=*
我有一個看似簡單的用例,但它困擾了我幾個小時
我有一個兩行兩列的網格,第一列應該采用所有可用的寬度,第二列應該采用它需要的寬度。 問題在於第二列的“所需寬度”。 此列在頂行包含一個數據網格,在底行包含一個標簽(為簡單起見)。 數據網格有兩列,它們都應占據數據網格寬度的 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>
這很臟,可能會讓我重新考慮我的設計,但它可以根據您的要求工作。 我不知道如何在不創建自定義控件或大量修改DataGrid
默認模板的情況下實現這一點,但這里是。
將您的DataGrid
樣式更改為此,並為Label
和DataGrid
命名。
<DataGrid Name="dg" ItemsSource="{Binding Items}" CanUserResizeColumns="False"/>
///
<Label Grid.Row="1" Grid.Column="1" Content="x" Name="label"/>
然后為您的MainWindow
創建一個ContentRendered
事件。
Title="MainWindow" Height="450" Width="800" Name="mw" ContentRendered="Mw_ContentRendered">
現在在渲染事件中,在渲染發生后手動調整列的大小。 您不能為寬度分配星號,因為它不會正確調整大小,因此您需要根據列數均勻划分寬度。
private void Mw_ContentRendered(object sender, EventArgs e)
{
//Loop through columns and resize
for (int x = 0; x < dg.Columns.Count; x++)
{
double div = dg.ActualWidth / dg.Columns.Count;
double add = div - dg.Columns[x].ActualWidth;
if (add < 0) { div += -add; }
dg.Columns[x].Width = new DataGridLength(div);
}
}
編輯:更新寬度邏輯以解決不均勻的寬度
我最終創建了自己的用戶控件。
這相對容易,因為我在設計時就知道我將在“datagridview”中包含哪些行。
Tronald 的建議有效,前提是數據在呈現后不會更改(我的建議是這樣,數據網格內容和“標簽”都根據在應用程序其余部分中所做的選擇而更改)。
我仍然認為 'Width="*" MinWidth="auto"' 組合應該適用於數據網格,所以如果有人有解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.