[英]How to set the width of Datagridcolumn based on the the width of the content placed in Datagrid cell
我想設置Datagridcolumn的寬度,以使列的寬度應基於放置在Datagrid單元格中的內容的大小,以使列之間的間距相等。
這是我到目前為止嘗試過的:
<DataGrid x:Name="MyGrid" AutoGenerateColumns="False" BorderBrush="Transparent"
GridLinesVisibility="None" Background="Transparent" RowHeaderWidth="0" >
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background" Value="Transparent" />
<Setter Property="FontFamily" Value="Segoe UI"/>
<Setter Property="FontWeight" Value="Normal"/>
<Setter Property="FontSize" Value="20"/>
<Setter Property="Padding" Value="0,5"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn Header = "Column 1">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding SomeText}" Width=120 TextWrapping="WrapWithOverflow" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn ..../>
<DataGridTemplateColumn ..../>
</DataGrid.Columns>
</Datagrid>
這樣的事情(如下所示),在列之間有相等的空間,並且根據數據網格單元格中定義的內容寬度來調整列。
這是您可以嘗試的方法,可以使用TextFomratter類( 假設您的網格僅包含text )來計算字符串寬度,因此您需要通過一種方法來計算最大列的寬度,可以通過使用綁定-RelativePath等
private Size MeasureString(string candidate)
{
var formattedText = new FormattedText(
candidate,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(this.textBlock.FontFamily, this.textBlock.FontStyle, this.textBlock.FontWeight, this.textBlock.FontStretch),
this.textBlock.FontSize,
Brushes.Black,
new NumberSubstitution(),
1);
return new Size(formattedText.Width, formattedText.Height);
}
您可以將上面的代碼與MultiConverter一起使用,以獲取對父Grid對象的引用,您可以將其與forloop一起使用以計算當前時間的最大寬度,從那里可能需要使用新的列寬來更新所有列。
您將需要文本+網格父對象作為多轉換器的參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.