在WPF中,要使用XAML标记在单击另一个控件时打开弹出窗口,可以使用Interaction.Triggers
和EventTrigger
来实现。以下是一个简单的示例,展示了如何在单击按钮时打开一个弹出窗口:
Window
,并添加一个按钮和一个弹出窗口: 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"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button x:Name="OpenPopupButton" Content="Open Popup" Margin="10"/>
<Popup x:Name="PopupWindow" Grid.Column="1" Placement="Right" Margin="10">
<Border Background="White" BorderBrush="Black" BorderThickness="1">
<StackPanel>
<TextBlock FontWeight="Bold" Margin="10">Popup Window</TextBlock>
<TextBlock Margin="10">This is a popup window.</TextBlock>
</StackPanel>
</Border>
</Popup>
</Grid>
</Window>
OpenPopupButton
的Interaction.Triggers
中添加一个EventTrigger
,并设置RoutedEvent
为Button.ClickEvent
。在EventTrigger
中添加一个BeginStoryboard
,并定义一个Storyboard
,将Popup
的IsOpen
属性设置为True
: 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"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button x:Name="OpenPopupButton" Content="Open Popup" Margin="10">
<Interaction.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="PopupWindow" Storyboard.TargetProperty="IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Interaction.Triggers>
</Button>
<Popup x:Name="PopupWindow" Grid.Column="1" Placement="Right" Margin="10">
<Border Background="White" BorderBrush="Black" BorderThickness="1">
<StackPanel>
<TextBlock FontWeight="Bold" Margin="10">Popup Window</TextBlock>
<TextBlock Margin="10">This is a popup window.</TextBlock>
</StackPanel>
</Border>
</Popup>
</Grid>
</Window>
现在,当您单击“Open Popup”按钮时,将打开一个弹出窗口。这个示例仅使用了XAML标记来实现功能,没有使用任何代码。
领取专属 10元无门槛券
手把手带您无忧上云