我正在尝试做一些从用户界面级别看起来相对简单和合乎逻辑的事情,但我有一个非常烦人的错误。我有一个 ToggleButton
并且我试图在切换按钮时显示 Popup
并在切换按钮时隐藏 Popup
。 Popup
也会在用户点击离开时隐藏。
在显示 Popup
后,我点击切换按钮时,Popup
会消失一瞬间然后重新出现。
以下 XAML 一切正常。
我怀疑这里发生的事情是点击远离 Popup
会导致它关闭按钮,然后在鼠标点击按钮时立即切换回按钮。我只是不知道如何修复它。
感谢任何帮助。谢谢。
<ToggleButton x:Name="TogglePopupButton" Content="My Popup Toggle Button" Width="100" />
<Popup StaysOpen="False" IsOpen="{Binding IsChecked, ElementName=TogglePopupButton, Mode=TwoWay}">
<Border Width="100" Height="200" Background="White" BorderThickness="1" BorderBrush="Black">
<TextBlock>This is a test</TextBlock>
</Border>
</Popup>
最佳答案
Stephans answers 有一个缺点,即失去焦点时关闭弹出窗口的预期行为也会消失。
我通过在弹出窗口打开时禁用切换按钮来解决它。另一种方法是使用 IsHitTestVisible 属性而不是启用:
<ToggleButton x:Name="TogglePopupButton" Content="My Popup Toggle Button" Width="100" IsEnabled="{Binding ElementName=ToggledPopup, Path=IsOpen, Converter={StaticResource BoolToInvertedBoolConverter}}"/>
<Popup x:Name="ToggledPopup" StaysOpen="False" IsOpen="{Binding IsChecked, ElementName=TogglePopupButton, Mode=TwoWay}">
<Border Width="100" Height="200" Background="White" BorderThickness="1" BorderBrush="Black">
<TextBlock>This is a test</TextBlock>
</Border>
</Popup>
转换器看起来像这样:
public class BoolToInvertedBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is bool)
{
bool boolValue = (bool)value;
return !boolValue;
}
else
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException("ConvertBack() of BoolToInvertedBoolConverter is not implemented");
}
}
关于c# - 如何正确地将 Popup 绑定(bind)到 ToggleButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14252180/