如何创建一个比其视觉区域更小的按钮区域的按钮?
问题描述:
我正在尝试使用较小的命中区域来创建按钮,以防止在工业触摸屏PC程序中出现误操作。这里是a sample, 只有the white area should response to touch and mouse operations.如何创建一个比其视觉区域更小的按钮区域的按钮?
我试着使用控件模板
<ControlTemplate x:Key="ButtonToTouch" TargetType="{x:Type Button}">
<Grid>
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}"/>
<Button Background="{x:Null}" BorderBrush="{x:Null}" FontSize="{TemplateBinding FontSize}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
<Button.Content>
<Grid Margin="8" >
<ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" />
<Rectangle Fill="Transparent" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
</Grid>
</Button.Content>
</Button>
</Grid>
</ControlTemplate>
现在鼠标输入事件这样工作,但似乎在按钮模板每一个可见的像素可以触发点击事件,所以我必须将边框的背景设置为null,并将模板中的背景设置在某处。
有什么建议吗?谢谢你的帮助。
答
设置IsHitTestVisible="False"
在边界上。在Grid上有8个边距时,8px宽的区域不会注册输入。
<ControlTemplate x:Key="ButtonToTouch" TargetType="{x:Type Button}">
<Grid>
<Border BorderBrush="{TemplateBinding BorderBrush}"
IsHitTestVisible="False"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"/>
<Grid Margin="8">
<ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" />
<Rectangle Fill="Transparent" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
</Grid>
</Grid>
</ControlTemplate>
我在代码中添加了'IsHitTestVisible =“False”'在边框上,它运行良好。然后,我尝试了你的,它的工作原理,但MouseOver上的所有动画和点击失败。也许我真的需要另一个按钮。谢谢你的帮助。 – foxsheep
@foxsheep,标准按钮模板包含在IsMouseOver = true或IsPressed = true时更改背景的模板触发器。 ButtonToTouch模板缺少这些触发器(通常在自定义控制模板时必须从基本模板复制它们)。 – ASh
添加''后效果很好,这比添加另一个按钮更加直接。再次感谢。 –
foxsheep