c# - 如何正确地将 Popup 绑定(bind)到 ToggleButton?

标签 c# wpf xaml popup togglebutton

我正在尝试做一些从用户界面级别看起来相对简单和合乎逻辑的事情,但我有一个非常烦人的错误。我有一个 ToggleButton 并且我试图在切换按钮时显示 Popup 并在切换按钮时隐藏 PopupPopup 也会在用户点击离开时隐藏。

在显示 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/

相关文章:

c# - 保存到数据库时字符串末尾的空格字符

c# - 是否有像 Queue 这样的 C# 类实现 IAsyncEnumerable?

.net - ReactiveUi:绑定(bind)到 ReactiveAsyncCommand 的按钮在使用一次后被禁用

wpf - 使用 slider 制作媒体播放器时间线

c# - 如何通过 Controller 返回另一个 Controller 的部分 View ?

c# - CLR运行时生成编译

wpf - 在 wpf mvvm 中单击按钮时将集合绑定(bind)到 xamdatagrid

wpf - 如何仅修改WPF控件的Margin属性的右侧(或左侧,顶部,底部)值?

c# - Xamarin.Forms.Xaml.XamlParseException : MarkupExtension not found

c# - 将当前前景绑定(bind)到 Rectangle.Fill 属性