WPF - 将 IsMouseOver 绑定(bind)到可见性

标签 wpf data-binding

我有一个窗口覆盖了 RadioButtonControlTemplate 以显示其中的自定义控件。在自定义控件中,我有一个按钮的可见性与 IsMouseOver 相关联,它仅在鼠标悬停在控件上时才能正常显示按钮。但是,当我单击 RadioButton 时,Button 消失了。经过一些调试和阅读后,RadioButton 似乎在单击时捕获鼠标,这使得 UserControlIsMouseOver 为 false。

我尝试将 Button 的可见性绑定(bind)到 FindAncestor {x:Type RadioButton} 并且它起作用了,但是让 对我来说似乎有点脆弱>UserControl 取决于包含它的人。窗口和用户控件的代码如下。有什么建议吗?

<Window x:Name="window" x:Class="WPFTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:WPFTest="clr-namespace:WPFTest"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <Style TargetType="{x:Type RadioButton}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type RadioButton}">
                        <WPFTest:TestUC />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Border BorderBrush="Black" BorderThickness="2">
        <StackPanel>
            <RadioButton x:Name="OptionButton" Height="100" />
            <TextBlock Text="{Binding ElementName=OptionButton, Path=IsMouseOver}" />
        </StackPanel>
    </Border>
</Window>

<UserControl x:Name="_this" x:Class="WPFTest.TestUC"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <UserControl.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
    </UserControl.Resources>
    <StackPanel>
        <TextBlock Text="SomeText" />
        <TextBlock Text="{Binding ElementName=_this, Path=IsMouseOver}" />
        <Button x:Name="_cancelTextBlock" Content="Cancel" Visibility="{Binding ElementName=_this, Path=IsMouseOver, Converter={StaticResource BooleanToVisibilityConverter}}" />
    </StackPanel>
</UserControl>

最佳答案

事件由 RadioButton 处理后,它只是设置已处理,但实际上它仍然冒泡。因此,您只需指定您也想处理已处理的事件。

为此,您需要查看 handledEventsToo .

不幸的是,我不认为它可以在 xaml 中设置。只有代码。

关于WPF - 将 IsMouseOver 绑定(bind)到可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/258824/

相关文章:

c# - 为什么不相关的属性也在 Winform 数据绑定(bind)中被多次调用,如何解决?

winforms - ObservableCollection(Of T) vs BindingList(Of T)?

c# - MVVM检测子类的属性变化

c# - 有没有更简单的方法来使用未知类型进行类型转换?

wpf - WPF 有颜色对话框吗?

c# - WPF DataGrid - 基于行动态绑定(bind) DataGridComboBoxColumn

android-studio - Android 中的 AutoCompleteTextView 或 Spinner 数据绑定(bind)

c# - 是否有可能以 mvvm 模式在 wpf datagrid 上获取动态列?

c# - WPF 将按钮绑定(bind)到命令

WPF:如何将对象绑定(bind)到组合框