我正在创建 WPF 应用程序的 UI,在致力于软件功能的实现时,我在创建 UI 方面没有太多经验。
现在我需要一种方法来更改“属性”面板的内容,该面板有一个网格来包含内容。我创建了多个面板,隐藏了除一个之外的所有面板,现在我想在用户单击顶部功能区中的按钮时进行切换(或者它可以是布局中其他位置的任何按钮)。
使用代码很容易完成,但我想在没有任何代码的情况下仅使用 XAML 来完成。怎么做?
另外如何将类似的行为绑定到 UI 上的其他项目?
我认为您选择的仅 XAML 解决方案将取决于您的具体要求。在下面的示例中,我假设仅 XAML 意味着您正在寻找不涉及绑定到 ViewModel 中的属性的解决方案。
方法#1:
如果您决定使用单个ToggleButton
显示和隐藏面板,那么这可以很容易地使用Triggers
:
<Window x:Class="WpfApplication1.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">
<ContentControl>
<ContentControl.Template>
<ControlTemplate>
<StackPanel>
<Grid x:Name="myGrid" Background="Beige" Height="100">
<TextBlock Text="Content Placeholder" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5"/>
</Grid>
<ToggleButton x:Name="toggleButton" Content="Show\Hide Panel" IsChecked="True"/>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger SourceName="toggleButton" Property="IsChecked" Value="True">
<Setter TargetName="myGrid" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger SourceName="toggleButton" Property="IsChecked" Value="False">
<Setter TargetName="myGrid" Property="Visibility" Value="Hidden" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
</Window>
方法#2:
如果您需要两个按钮(一个用于显示面板,一个用于隐藏面板),那么也许您可以使用EventTrigger
反而。这个解决方案更加严厉,因为EventTrigger
不使用Setter
而是它的动作必须是Storyboard
。模拟属性的设置,例如Visibility
您可以使用ObjectAnimationUsingKeyFrames
在你的Storyboard
:
<Window x:Class="WpfApplication1.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">
<StackPanel>
<Grid x:Name="myGrid" Background="Beige" Height="100">
<TextBlock Text="Content Placeholder" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5"/>
</Grid>
<Button x:Name="showPanelButton" Content="Show Panel" />
<Button x:Name="hidePanelButton" Content="Hide Panel" />
<StackPanel.Triggers>
<EventTrigger RoutedEvent="UIElement.PreviewMouseLeftButtonUp" SourceName="showPanelButton">
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="myGrid" Storyboard.TargetProperty="(UIElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.PreviewMouseLeftButtonUp" SourceName="hidePanelButton">
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="myGrid" Storyboard.TargetProperty="(UIElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Hidden}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</StackPanel.Triggers>
</StackPanel>
</Window>
希望这可以帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)