假设您有一个ToggleButton
用于打开 a 的,与所有已知元素等Popup
相同的行为。ComboBox
...这是这段代码:
<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>
然后在你背后的代码中使用 . IsOpen
对于Popup
和 。IsChecked
为ToggleButton
. 一切正常,但是当您打开Popup
并单击边界外时,问题就来了。将Popup
关闭,但ToggleButton
保持检查。
您不能在PopupOnClosed
Handler 中设置ToggleButton.IsChecked = false
,因为当您单击ToggleButton
关闭 时Popup
,Popup
关闭本身,设置ToggleButton.IsChecked = false
但在您单击的同时ToggleButton
它会尝试Popup
再次打开。所以你不能关闭它。
第一个切换按钮单击:
-> ToggleButton IsChecked = true
第二个切换按钮单击:
-> ToggleButton IsChecked = false
-> ToggleButton IsChecked = true
因此,如果您在弹出窗口打开时单击切换按钮,它会闪烁但保持打开状态。
请问这个问题怎么解决?
编辑:
请在 MyWindow.XAML 中尝试此操作,并在后面的代码中添加依赖属性 IsDropDownOpen,请:
<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));