我有一个数据网格,其行显示或消失,具体取决于某些用户首选项。 此数据网格是包含一些这些网格的堆栈面板的一部分。 问题是当用户隐藏某些行时,数据网格高度不会缩小。这只发生在Windows XP上,而不是在Windows 7上,网格会按预期收缩。
以下是一个显示问题的小例子:
xaml:
<Window x:Class="TestDataGridResize.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" Loaded="Window_Loaded">
<Grid>
<StackPanel Orientation="Vertical">
<Button Content="Hide some rows" Click="Button_Click"/>
<DataGrid Name="dataGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True" Binding="{Binding Name}" Header="Name" />
</DataGrid.Columns>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Visibility" Value="{Binding Visibility}"/>
</Style>
</DataGrid.RowStyle>
</DataGrid>
<TextBlock Text="THE END" Background="AliceBlue" TextAlignment="Center"/>
</StackPanel>
</Grid>
背后的代码:
public partial class MainWindow : Window
{
private ObservableCollection<Element> elements = new ObservableCollection<Element>();
public MainWindow()
{
InitializeComponent();
this.dataGrid.ItemsSource = this.elements;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 5; i++)
this.elements[i].Visibility = System.Windows.Visibility.Collapsed;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 10; i++)
this.elements.Add(new Element("Element " + i));
}
}
public class Element : INotifyPropertyChanged
{
private static PropertyChangedEventArgs VisibilityChanged = new PropertyChangedEventArgs("Visibility");
private string name;
public string Name
{
get { return this.name; }
set { this.name = value; }
}
private Visibility visibility;
public Visibility Visibility
{
get { return this.visibility; }
set
{
this.visibility = value;
if (this.PropertyChanged != null)
this.PropertyChanged(this, VisibilityChanged);
}
}
public Element(string name)
{
this.name = name;
}
public event PropertyChangedEventHandler PropertyChanged;
}
目标框架是4.0。 任何帮助将不胜感激。
答案 0 :(得分:0)
尝试使用Grid
来排列控件而不是StackPanel
:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Content="Hide some rows" Click="Button_Click"/>
<DataGrid Grid.Row="1" Name="dataGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True" Binding="{Binding Name}" Header="Name" />
</DataGrid.Columns>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Visibility" Value="{Binding Visibility}"/>
</Style>
</DataGrid.RowStyle>
</DataGrid>
<TextBlock Grid.Row="2" Text="THE END" Background="AliceBlue" TextAlignment="Center"/>
</Grid>