4

我遇到了一个问题,带有路径内容的按钮仅检测路径的鼠标点击。对于 ux,我想在按钮的任何位置注册点击。我已将按钮的背景设置为 null 和透明,因此顶部控件容器决定了背景样式。

这是另一个 SO 帖子:透明背景上的鼠标事件

如前所述,到目前为止,我已经尝试过透明和 null。

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:wpfMyCustomControl">

<ControlTemplate x:Key="IconTemplate" TargetType="{x:Type ContentControl}">
    <Grid>
        <Path Name="ForegroundSymbol" Data="M0,0 L1,0 1,1 0,1 0.5,0.5 z" Fill="{TemplateBinding Foreground}" Stretch="Fill" />
    </Grid>
</ControlTemplate>

<Style x:Key="IconButtonStyle" TargetType="{x:Type RepeatButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type RepeatButton}">
                <Grid>
                    <ContentControl Name="icon" Template="{StaticResource IconTemplate}" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


<ControlTemplate x:Key="MyCustomTemplate" TargetType="{x:Type local:MyCustomControl}">
    <Grid Name="LayoutRoot" Background="Red">
        <RepeatButton Background="{x:Null}" Style="{StaticResource ResourceKey=IconButtonStyle}" />
    </Grid>
</ControlTemplate>

<Style TargetType="{x:Type local:MyCustomControl}">
    <Setter Property="Template" Value="{StaticResource ResourceKey=MyCustomTemplate}" />
</Style>
</ResourceDictionary>

如果我从“样式”中删除“x:Key”属性,控件就会呈现。我已经能够使用上述 xaml 控件样式重现该问题,其中点击检测不会在按钮的“背景”部分触发。

4

3 回答 3

6

您应该使用几乎透明的背景,而不是使用透明背景 。这样,Click-event 仍然会被触发,但按钮仍然看起来是透明的。
就像是:

<RepeatButton Background="#01FFFFFF" Style="{StaticResource ResourceKey=IconButtonStyle}" />

颜色定义的前两位数字定义了TransparencyorAlpha值。

于 2013-03-04T13:19:10.557 回答
1

如果您实际使用背景是透明的,HitTesting 将起作用。您正在应用样式但未包含样式,所以我不能说,但如果在该样式中您正在设置模板并且您没有在 ControlTemplate 中使用背景,那么设置背景是没有意义的。通常,模板中根元素的背景会与背景(通常是面板或边框)进行 TemplateBinding。元素本身不使用背景。另一种选择是覆盖 HitTestCore 方法。您可以在 Reflector/ILSpy 中查看 TextBlock 的实现,因为它会覆盖它以确保其矩形内的任何点(而不仅仅是文本的字符)都是有效的命中点。

编辑:根据您提供的样式/模板,问题就是我所描述的。您需要在ControlTemplate中使用背景,否则不会产生任何影响。所以IconTemplate应该看起来像:

<ControlTemplate x:Key="IconTemplate" TargetType="{x:Type ContentControl}">
    <Grid Background="{TemplateBinding Background}">
        <Path Name="ForegroundSymbol" Data="M0,0 L1,0 1,1 0,1 0.5,0.5 z" Fill="{TemplateBinding Foreground}" Stretch="Fill" />
    </Grid>
</ControlTemplate>
于 2013-03-02T03:46:17.087 回答
0

如果您不想设置颜色而不是设置透明,则需要为命中检测提供背景颜色。

于 2013-03-04T12:59:12.240 回答