其他元素折叠时 WPF UI 元素不会增长
Posted
技术标签:
【中文标题】其他元素折叠时 WPF UI 元素不会增长【英文标题】:WPF UI element not growing when other element gets collapsed 【发布时间】:2021-03-18 04:33:36 【问题描述】:我希望元素在其他元素折叠时占据新的可用空间(例如宽度)。在我的示例中,当我折叠复选框时,第一个按钮没有变宽。我在这里做错了什么?谢谢!
XAML:
<Window x:Class="WpfApp3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Width="250" Height="150"
Title="MainWindow">
<StackPanel Width="200" Height="80">
<StackPanel Orientation="Horizontal">
<Button Height="25" Margin="5" Content="Button 1"/>
<CheckBox Content="Checkbox" VerticalAlignment="Center" Visibility="Binding CheckBoxVisibility"/>
</StackPanel>
<Button Height="25" Margin="5" Content="Change visibility" Click="Button_Click"/>
</StackPanel>
</Window>
后面的代码:
using System.Windows;
namespace WpfApp3
public partial class MainWindow : Window
public MainWindow()
InitializeComponent();
DataContext = new MainViewModel();
private MainViewModel _viewModel => DataContext as MainViewModel;
private void Button_Click(object sender, RoutedEventArgs e)
if (_viewModel.CheckBoxVisibility == Visibility.Visible)
_viewModel.CheckBoxVisibility = Visibility.Collapsed;
else if (_viewModel.CheckBoxVisibility == Visibility.Collapsed)
_viewModel.CheckBoxVisibility = Visibility.Hidden;
else
_viewModel.CheckBoxVisibility = Visibility.Visible;
视图模型:
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
namespace WpfApp3
public class MainViewModel : INotifyPropertyChanged
public MainViewModel()
CheckBoxVisibility = Visibility.Hidden;
public event PropertyChangedEventHandler PropertyChanged;
private Visibility _checkBoxVisibility;
public Visibility CheckBoxVisibility
get => _checkBoxVisibility;
set
_checkBoxVisibility = value;
OnPropertyChanged();
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
【问题讨论】:
【参考方案1】:水平 StackPanel 中的元素不会水平拉伸,它们占用最小的宽度。
<StackPanel Orientation="Horizontal">
<Button Height="25" Margin="5" Content="Button 1"/>
<CheckBox Content="Checkbox" VerticalAlignment="Center" Visibility="Binding CheckBoxVisibility"/>
</StackPanel>
将 StackPanel 替换为 Grid
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Button Height="25" Margin="5" Content="Button 1" Grid.Column="0"/>
<CheckBox Content="Checkbox" Grid.Column="1"
VerticalAlignment="Center"
Visibility="Binding CheckBoxVisibility"/>
</Grid>
【讨论】:
非常感谢,不知道。对于其他读者:重要的是首先是“*”,然后是“自动”列宽。 @IngoB,"*" first, then "Auto"
- 不完全是。自动宽度列的顺序不会改变它的行为。宽度取决于该列内元素的宽度。交换按钮和复选框 - 你必须交换列定义
是的,当然,这就是我的意思。谢谢。以上是关于其他元素折叠时 WPF UI 元素不会增长的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Flutter 中折叠其他 ExpansionTile 元素
Bootstrap 4展开全部/全部折叠按钮在折叠元素已经显示时不起作用