我在 WPF 中有一堆具有透明背景的工具条按钮。当用户将鼠标悬停在按钮外部时,什么也不会发生,因为按钮的那部分是透明的。一旦用户将鼠标悬停在按钮的非透明区域之一上,“悬停”行为就会更改边框和背景颜色。背景不再透明,因此悬停行为会在比以前更大的区域继续。我希望按钮的透明区域表现得好像按钮在那里是不透明的。
也就是说,现在我有这种行为,尽管鼠标明显位于按钮区域内,但按钮未被选中:
即使用户之前没有将鼠标悬停在按钮的前景“白色”部分上,我也试图让按钮像这样被选中:
我尝试在按钮本身上设置 IsHitTestVisible
,但这似乎没有任何区别。
有没有办法让 WPF 认为按钮的透明区域很重要?
XAML 目前看起来像这样:
<Button Style="{StaticResource MainToolstripButtonStyle}" Margin="5,0,0,0"
ToolTip="{StaticResource OpenButtonText}"
AutomationProperties.Name="{StaticResource OpenButtonText}"
Command="{StaticResource Open}"
Content="{StaticResource OpenIcon}" />
<Style x:Key="MainToolstripButtonStyle" TargetType="Button">
<Setter Property="Width" Value="24" />
<Setter Property="Height" Value="24" />
<Setter Property="Background" Value="{x:Null}" />
<Setter Property="Foreground" Value="White" />
<Setter Property="Padding" Value="0" />
<!-- If users want to use keyboard navigation, they use the menu instead. -->
<Setter Property="IsTabStop" Value="False" />
<Setter Property="Focusable" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Name="Border"
BorderThickness="1"
BorderBrush="{x:Null}">
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"
RecognizesAccessKey="True" />
</Border>
<ControlTemplate.Triggers>
<!-- Low contrast triggers for selection / focus / enabled: -->
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Source={x:Static vvm:SystemParametersBindingTarget.Instance}, Path=HighContrast}" Value="False" />
<Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsMouseOver}" Value="True" />
<Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter TargetName="Border"
Property="Background"
Value="{StaticResource HotToolbarButtonBrush}" />
<Setter TargetName="Border"
Property="BorderBrush"
Value="{StaticResource HotToolbarButtonBorderBrush}" />
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Source={x:Static vvm:SystemParametersBindingTarget.Instance}, Path=HighContrast}" Value="False" />
<Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled}" Value="False" />
</MultiDataTrigger.Conditions>
<Setter Property="Foreground"
Value="{StaticResource DisabledToolbarButtonBrush}" />
</MultiDataTrigger>
<!-- High contrast triggers omitted -->
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
最佳答案
替换
<Setter Property="Background" Value="{x:Null}" />
通过
<Setter Property="Background" Value="Transparent" />
并使用 ControlTemplate 中的 Background 属性:
<ControlTemplate TargetType="{x:Type Button}">
<Border Name="Border" Background="{TemplateBinding Background}" ...>
...
</Border>
</ControlTemplate>
关于c# - 如何在 WPF 中使按钮的透明部分可单击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29635353/