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