簡體   English   中英

WPF 數據網格 MinWidth=auto MaxWidth=*

[英]WPF datagrid MinWidth=auto MaxWidth=*

我有一個看似簡單的用例,但它困擾了我幾個小時

我有一個兩行兩列的網格,第一列應該采用所有可用的寬度,第二列應該采用它需要的寬度。 問題在於第二列的“所需寬度”。 此列在頂行包含一個數據網格,在底行包含一個標簽(為簡單起見)。 數據網格有兩列,它們都應占據數據網格寬度的 50%。

我想要:

  • 如果標簽比數據網格寬,則數據網格應按比例放大(並且在填充剩余空間的數據網格末尾可能不會出現半列)
  • 如果數據網格比標簽寬,則該列不得小於數據網格所需的大小。

問題:

  • 如果我將 datagrid 列設置為占用所有可用空間 (width='*'),則如果標簽大於 datagrid(但如果標簽較小,則 datagrid 會縮小到標簽的寬度,而不是 al 文本)可讀)
  • 如果我將列設置為“自動調整大小”,它的工作原理是標簽小於數據網格(但如果標簽更大,則會出現“半”列(這真的傷害了我的眼睛))。

編碼:

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 是一個對象列表(包含兩個字符串值)

這很臟,可能會讓我重新考慮我的設計,但它可以根據您的要求工作。 我不知道如何在不創建自定義控件或大量修改DataGrid默認模板的情況下實現這一點,但這里是。

將您的DataGrid樣式更改為此,並為LabelDataGrid命名。

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM