【发布时间】:2011-01-20 23:48:43
【问题描述】:
假设您有一个ToggleButton 用于打开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 for Popup 和 .IsChecked for 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));
【问题讨论】:
标签: wpf popup hide togglebutton