使用文本换行调整数据网格高度不正确
本文关键字:数据网 网格 高度 不正确 数据 调整 文本 换行 | 更新日期: 2023-09-27 18:20:30
问题
我在wpf应用程序中有一个DataGrid
。这个问题与DataGrid
在某些窗口大小调整事件后的外观有关。每当用户缩小窗口然后再次放大时,DataGrid
的行都会缩小(因为文本换行),但DataGrid
本身的高度不会缩小。由此产生的效果是DataGrid
周围似乎有一个太长的边界。一旦用户降低窗口的高度,此边框就会缩小。启动应用程序时,此边界也太长。
Xaml
<Window x:Class="SampleApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="WrappingTextBlock" TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
</Style>
<Style x:Key="WrappingTextBox" TargetType="TextBox">
<Setter Property="TextWrapping" Value="Wrap"/>
</Style>
</Window.Resources>
<Grid>
<Border>
<ScrollViewer>
<StackPanel>
<DataGrid ItemsSource="{Binding Objects}" HorizontalAlignment="Stretch" Margin="5" AutoGenerateColumns="False" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled">
<DataGrid.Columns>
<DataGridTextColumn MinWidth="15" Width="Auto" Header="#" Binding="{Binding Number}"/>
<DataGridTextColumn MinWidth="65" Width="Auto" Header="Style" Binding="{Binding Style}"/>
<DataGridTextColumn MinWidth="80" Width="*" Header="Description" Binding="{Binding Description}" ElementStyle="{StaticResource WrappingTextBlock}" EditingElementStyle="{StaticResource WrappingTextBox}"/>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</ScrollViewer>
</Border>
</Grid>
</Window>
代码隐藏
using System.Collections.Generic;
using System.Windows;
namespace SampleApp {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
DataContext = new ViewModel();
}
}
public class ViewModel {
public ViewModel() {
Objects = new List<MyObject>() {
new MyObject() { Number=1, Style="Good Style", Description="Small description", },
new MyObject() { Number=2, Style="Bad Style", Description="This is a medium length description that you are reading.", },
new MyObject() { Number=3, Style="Awesome Style", Description="This is a long description that you are reading because I repeat the message. This is a long description that you are reading because I repeat the message.", },
};
}
public List<MyObject> Objects { get; set; }
}
public class MyObject {
public MyObject() { }
public int Number { get; set; }
public string Style { get; set; }
public string Description { get; set; }
}
}
加载后,将代码后面的该列的TextWrapping设置为Wrap。为我工作。