我有一个窗口,覆盖了一个RadioButton的ControlTemplate以在其内部显示自定义控件。在自定义控件中,我将一个按钮的可见性与IsMouseOver绑定,当鼠标悬停在控件上时,它能够正确地显示按钮。但是,当我单击RadioButton时,按钮消失了。经过调试和阅读资料,似乎RadioButton在单击时会捕获鼠标,这会使UserControl的IsMouseOver变为false。
我尝试将Button的可见性绑定到FindAncestor {x:Type RadioButton},它可以工作,但我认为让UserControl依赖于包含它的对象有点脆弱。下面是窗口和用户控件的代码。有什么建议吗?
我尝试将Button的可见性绑定到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>