On a recent WPF project we had need of a Popup that would display when a ToggleButton was Checked, not display when Unchecked, and also disappear whenever the user clicked anywhere in the view.
The solution was straightforward: Use Popup.StaysOpen=False, and use data binding on the Popup.IsOpen property to the ToggleButton.IsChecked property (in the below code example, assume a ToggleButton named ExpandPresetList):
<
PopupName="PresetPopup"IsOpen="{Binding ElementName=ExpandPresetList, Path=IsChecked}"PlacementTarget="{Binding ElementName=DefaultAudiogramPresetsContainer}"AllowsTransparency="True"PopupAnimation="Slide"StaysOpen="False"/>
Well, this worked great, until you try to use the ToggleButton to no longer show the Popup. What would happen is that the Popup.StaysOpen property would collide with the data binding to the Popup.IsOpen property, and cause the Popup to never close when you click on the ToggleButton.
The solution was to bind to the ToggleButton.MouseEnter and ToggleButton.MouseLeave properties and modify the Popup.StaysOpen property whenever the user was using the ToggleButton.
Example:
<
ToggleButtonName="ExpandPresetList"Width="13"Height="13"VerticalAlignment="Center"HorizontalAlignment="Right"Margin="2.5 0 2.5 0"Style="{StaticResource roundExpandGraphicToggleButtonStyle}"MouseEnter="ExpandPresetList_MouseEnter"MouseLeave="ExpandPresetList_MouseLeave"/>
The event handlers for MouseEnter and MouseLeave look as follows:
private
void ExpandPresetList_MouseEnter(object sender, MouseEventArgs e){
true;PresetPopup.StaysOpen =
}
privatevoid ExpandPresetList_MouseLeave(object sender, MouseEventArgs e)
{
false;PresetPopup.StaysOpen =
}
The above examples let you use a Popup, data bound to a ToggleButton and have the Popup disappear whenever the user clicks anywhere, as well as use the ToggleButton to make the Popup disappear.
This seemed like an elegant solution, does anyone have a good alternate solution, maybe one that doesn't involve code, and can be done in pure XAML? I didn't see any properties on Popup that would assist in resolving the data binding event storm that results when using Popup.StaysOpen and ToggleButton.IsChecked.