Reputation: 1001
My requirement is to control the closing/opening of popup from a Button. In my below piece of code by clicking on button the popup opens up but it doesn't closes on the next click.
XAML
<Button x:Name="Btn" Height="20" Width="120" HorizontalAlignment="Center"
VerticalAlignment="Center">
<TextBlock Text="Show Popup"/>
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames
Storyboard.TargetName="Popup"
Storyboard.TargetProperty="IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Button.Triggers>
</Button>
<Popup x:Name="Popup" StaysOpen="False"
Height="100" Width="300" Background= "Yellow"
PlacementTarget="{Binding ElementName=Btn}"></Popup>
Note: I am able to achieve the above case using a Toggle button, But my requirement is very specific to button only.
Upvotes: 0
Views: 1756
Reputation: 29028
You can't do it without toggling i.e. Button
alone can't do it. You are handling a control that has a state: opened and closed. You need to know the current state. To achieve this, add a flag to the hosting control (requires code-behind) or use the flag of the Popup
(requires code-behind) or use the flag of the ToggleButton
(no code-behind).
It doesn't make any sense to avoid the ToggleButton
: it's a Button
that additionally knows or has a state. It can handle ICommand
or emit a Click
event - it's a Button
. It's exactly what you need.
You don't have to explicitly add a TextBlock
to the Content
of the Button
. When assigning a string to Button.Content
, the control will automatically create a TextBlock
to show the string.
MainWindow.xaml
<Button Click="TogglePopup_OnClick"
Content="Show Popup" />
<Popup x:Name="Popup" />
MainWindow.xaml.cs
private void TogglePopup_OnClick(object sender, EventArgs e)
=> this.Popup.IsOpen ^= true;
Upvotes: 1