如何更新StackPanel的布局?

问题是,如果您单击按钮并展开电话号码,堆栈面板和边框会展开,这很好,但如果您折叠它,堆栈面板和边框不会折叠。

         

使用以下代码隐藏:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); myListBox.ItemsSource = new List() { 1, 2 }; //add 2 elements; } private void Button_Click(object sender, RoutedEventArgs e) { Button btn = sender as Button; StackPanel sp1 = VisualTreeHelper.GetParent(btn) as StackPanel; StackPanel sp2 = VisualTreeHelper.GetParent(sp1) as StackPanel; StackPanel phone = sp2.FindName("PhoneNumber") as StackPanel; if (phone.Visibility == System.Windows.Visibility.Collapsed) phone.Visibility = System.Windows.Visibility.Visible; else phone.Visibility = System.Windows.Visibility.Collapsed; myListBox.UpdateLayout(); //these don't collapse my space this.UpdateLayout(); //these don't collapse my space } } } 

没有深入研究这一点,但看起来你必须将链中的InvalidateMeasure调用到ItemsPresenter (实际上是ItemsPresenter )。 如果我能用更好的东西,我会更新

 private void Button_Click(object sender, RoutedEventArgs e) { Button btn = sender as Button; StackPanel sp1 = VisualTreeHelper.GetParent(btn) as StackPanel; StackPanel sp2 = VisualTreeHelper.GetParent(sp1) as StackPanel; StackPanel phone = sp2.FindName("PhoneNumber") as StackPanel; if (phone.Visibility == System.Windows.Visibility.Collapsed) phone.Visibility = System.Windows.Visibility.Visible; else phone.Visibility = System.Windows.Visibility.Collapsed; DependencyObject dpObject = btn; while (dpObject != null) { if (dpObject is UIElement) { (dpObject as UIElement).InvalidateMeasure(); } if (dpObject is ItemsPresenter) break; dpObject = VisualTreeHelper.GetParent(dpObject); } } 

问题是Listbox正在使用虚拟化。 如果你禁用它,那么问题就会消失,就像这样:

        

或者,您可以保留默认的ItemsPanel并在ListBox上设置ScrollViewer.CanContentScroll="False" 。 两者都禁用虚拟化。

我相信这个问题是有关系的。