gpt4 book ai didi

WPF弹出隐藏问题

转载 作者:行者123 更新时间:2023-12-04 20:22:50 29 4
gpt4 key购买 nike

假设你有一个 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>

然后在你背后的代码中使用 . IsOpenPopup和 。 IsCheckedToggleButton .
一切正常,但是当您打开 Popup 时问题就来了并在边框外单击。 Popup将被关闭,但 ToggleButton 保持检查 .

您不能在 PopupOnClosed 中设置处理程序 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));

最佳答案

我在这篇文章中找到了解决方案:https://stackoverflow.com/a/5821819/651161

使用以下类将允许在按下切换按钮之前处理点击。由于单击,弹出窗口已关闭,但随后处理了单击,因此不会触发 ToggleButton 单击。

public class MyPopup : Popup {
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e) {
bool isOpen = this.IsOpen;
base.OnPreviewMouseLeftButtonDown(e);

if (isOpen && !this.IsOpen)
e.Handled = true;
}
}

关于WPF弹出隐藏问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2333905/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com