我试图在按钮点击时显示一个折叠的堆叠面板,但我遇到了问题所以我试图改变我的想法,我能够折叠一个可见的堆叠面板。但不幸的是,我无法实现我想要的行为,在按钮点击时显示折叠的堆栈面板。代码:D
XAML
<Button x:Name="sentButton" Content="Add Friend" Style="{DynamicResource FlatButtonStyle}" Margin="493,0,0,0" HorizontalAlignment="Left" Width="106"/>
<StackPanel Style="{DynamicResource stackCollapsed}" Visibility="Collapsed">
<Label Content="Invite Friends" FontWeight="Bold" Margin="0,0,477,0" Height="32" />
<StackPanel Orientation="Horizontal" Margin="26,0,0,0">
<Label Content="Enter your friend's email" Width="222" Height="25" />
<TextBox Text="{Binding Email, UpdateSourceTrigger=PropertyChanged}" Style="{DynamicResource MyTextBox}" x:Name="textBoxEmail" Width="298"/>
<Button x:Name="button1" Content="Send" Command="{Binding AddCommand}" Width="77" Style="{DynamicResource FlatButtonStyle}" Margin="20,0,0,0"/>
</StackPanel>
</StackPanel>
样式
<!-- Style Collapsed-->
<Style x:Key="stackCollapsed" TargetType="StackPanel">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=sentButton,Path=IsPressed}" Value="true">
<Setter Property="StackPanel.Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
答案 0 :(得分:3)
而不是Button
使用ToggleButton
并通过StackPanel.Visibility
转换器将ToggleButton.IsChecked
绑定到BooleanToVisibilityConverter
属性
<ToggleButton x:Name="sentButton" Content="Add Friend" Margin="493,0,0,0" HorizontalAlignment="Left" Width="106"/>
<StackPanel Visibility="{Binding ElementName=sentButton, Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}">
<Label Content="Invite Friends" FontWeight="Bold" Margin="0,0,477,0" Height="32" />
<StackPanel Orientation="Horizontal" Margin="26,0,0,0">
<Label Content="Enter your friend's email" Width="222" Height="25" />
<TextBox Text="{Binding Email, UpdateSourceTrigger=PropertyChanged}" x:Name="textBoxEmail" Width="298"/>
<Button x:Name="button1" Content="Send" Command="{Binding AddCommand}" Width="77" Margin="20,0,0,0"/>
</StackPanel>
</StackPanel>
其中转换器定义如下
<Window.Resources>
<ResourceDictionary>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</ResourceDictionary>
</Window.Resources>
答案 1 :(得分:1)
问题是Visibility
选项卡中的<StackPanel>
属性优先于样式或触发器中设置的任何内容,因此永远不会应用触发器。有关详细信息,请参阅Dependency Property Precedence List。
要修复当前的解决方案,请将Visibliity属性移出<StackPanel>
标记并移入您的样式,如下所示:
<Style x:Key="stackCollapsed" TargetType="StackPanel">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=sentButton,Path=IsPressed}" Value="true">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
<StackPanel Style="{DynamicResource stackCollapsed}">
...
</StackPanel>
那就是说,我个人会推荐类似于切换按钮的内容,StackPanel.Visibility
绑定到ToggleButton.IsChecked
,例如this answer suggests。
答案 2 :(得分:0)
我解决了将Children设置为null
stackPanel.Children.Clear();
如果您是第一次需要显示/隐藏面板,则可以使用此功能,如果需要运行时,则无法使用
答案 3 :(得分:0)
就像Stackpanel一样简单。Visibility= Visibility.Collapsed。