我对 .NET 4.0 DataGrid 有一个非常令人不安的问题。我有比例模板列,其中包含启用了 textWrapping 的 TextBlock。
问题是,DataGrid 的高度在加载时不正确(它的大小就像文本块都被最大包装一样。)并且在调整大小时不会更新它们的大小。这似乎是一个布局问题(当比例大小未解决时,似乎调用了 MeasureOverride 和 ArrangeOverride ,之后未调用......)但我无法解决它。
这是显示问题的简化代码:
主窗口.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="700" Width="525">
<StackPanel Width="500">
<Button Content="Add DataGrid" Click="Button_Click" />
<ItemsControl x:Name="itemsControl">
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Control.Margin" Value="5" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
</StackPanel>
主窗口.xaml.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
namespace WpfApplication1
{
public partial class MainWindow : System.Windows.Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
itemsControl.Items.Add(CreateDataGrid());
}
private DataGrid CreateDataGrid()
{
var dataGrid = new DataGrid() { HeadersVisibility = DataGridHeadersVisibility.Column };
dataGrid.MaxWidth = 500;
dataGrid.Background = Brushes.LightSteelBlue;
dataGrid.Columns.Add(GetDataGridTemplateColumn("Label", "Auto"));
dataGrid.Columns.Add(GetDataGridTemplateColumn("Value", "*"));
dataGrid.Items.Add(new Entry() { Label = "Text Example 1", Value = "Some wrapped text" });
dataGrid.Items.Add(new Entry() { Label = "Text Example 2", Value = "Some wrapped text" });
return dataGrid;
}
private DataGridTemplateColumn GetDataGridTemplateColumn(string bindingPath, string columnWidth)
{
DataGridTemplateColumn result = new DataGridTemplateColumn() { Width = (DataGridLength)(converter.ConvertFrom(columnWidth))};
FrameworkElementFactory cellTemplateframeworkElementFactory = new FrameworkElementFactory(typeof(TextBox));
cellTemplateframeworkElementFactory.SetValue(TextBox.NameProperty, "cellContentControl");
cellTemplateframeworkElementFactory.SetValue(TextBox.TextProperty, new Binding(bindingPath));
cellTemplateframeworkElementFactory.SetValue(TextBox.TextWrappingProperty, TextWrapping.Wrap);
result.CellTemplate = new DataTemplate() { VisualTree = cellTemplateframeworkElementFactory };
return result;
}
private static DataGridLengthConverter converter = new DataGridLengthConverter();
}
public class Entry
{
public string Label { get; set; }
public string Value { get; set; }
}
}