Suppose you have a ToggleButton to open a Popup , the same behavior as all known elements like a ComboBox , etc.
... which is this code:
<ToggleButton x:Name="PART_OpenToggleButton" Focusable="False" IsChecked="False" Template="{StaticResource MyToggleButton}"> <Grid> <Popup x:Name="PART_PopupControl" Style="{StaticResource MyPopupStyle}" StaysOpen="False" VerticalAlignment="Bottom" IsOpen="False" PlacementTarget="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ToggleButton, AncestorLevel=1}}" /> </Grid> </ToggleButton>
Then in the code behind you work with. IsOpen for Popup and. IsChecked for ToggleButton . Everything works, but the problem occurs when you open Popup and click outside the borders. Popup will close, but ToggleButton will remain checked .
You cannot set in the PopupOnClosed handler that ToggleButton.IsChecked = false , because when you click ToggleButton to close the Popup , Popup closes, sets ToggleButton.IsChecked = false , but at that time you clicked on ToggleButton , and it tries again open Popup . Therefore, you cannot close it.
1st ToggleButtonClick:
-> ToggleButton IsChecked = true
2nd ToggleButtonClick:
-> ToggleButton IsChecked = false -> ToggleButton IsChecked = true
So, if you press the Toggle button while opening the Popup, it will start flashing, but remain open.
How would you solve this problem, please?
Edition:
Try this in MyWindow.XAML and add the IsDropDownOpen dependency property in the code behind, please:
<Grid> <ToggleButton x:Name="PART_OpenToggleButton" Focusable="False" Height="20" Width="50" IsChecked="{Binding ElementName=TestWindow, Mode=TwoWay, Path=IsDropDownOpen}"> <Grid> <Popup x:Name="PART_PopupControl" Width="100" Height="100" StaysOpen="False" Focusable="False" VerticalAlignment="Bottom" IsOpen="{Binding ElementName=TestWindow, Path=IsDropDownOpen}" PlacementTarget="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ToggleButton, AncestorLevel=1}}"> </Popup> </Grid> </ToggleButton> </Grid> public bool IsDropDownOpen { get { return (bool)GetValue(IsDropDownOpenProperty); } set { SetValue(IsDropDownOpenProperty, value); } } public static readonly DependencyProperty IsDropDownOpenProperty = DependencyProperty.Register("IsDropDownOpen", typeof(bool), typeof(Window), new UIPropertyMetadata(false));