[英]WPF Command Not Firing on Image Button Click
我正在尝试使播放器(某种)控件。 我已经有一个可用的用户控件按钮(公司控件)。 我正在尝试使按钮的形状与添加到其内容中的图像相同。
问题是当我删除模板样式(根据图像边界适合我的按钮边界)时,当我尝试单击按钮时,无法触发关联的ToolBarCommand。 本质上,我无法单击按钮本身。
对此并没有多大帮助,我尝试对图像使用IsHitTestVisible="False"
-但这也没有帮助。
以下是我的代码:
<my:NewButton Command="{Binding ToolBarCommand}" CommandParameter="Play">
<my:NewButton.Style>
<Style>
<Setter Property="my:NewButton.Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type my:NewButton}">
<ContentPresenter HorizontalAlignment=" TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</my:NewButton.Style>
<my:NewButton.Content>
<Image Source="{Binding PlayState}" IsHitTestVisible="False" />
</my:NewButton.Content>
</my:NewButton>
任何帮助深表感谢。 PS:VS2012,.net 4.0
您需要一些非空的颜色并在按钮的可视树中命中测试可见像素,以使其具有命中测试可见性。
您故意在图像上设置IsHitTestVisible="False"
。 如果将其删除,它应该可以工作,并且图像具有透明像素-这些像素不会“感觉”到点击。
如果图像上必须有IsHitTestVisible="False"
,则在控件模板中:
<Border Background="Transparent">
<ContentPresenter HorizontalAlignment=" TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
边框将成为“感觉”鼠标单击的边框。
您甚至可以在按钮上设置“ Padding
”,并具有比图像更大的点击测试区域。
应用ControlTemplate
功能时, ControlTemplate
的外观应完全改变。 ContentPresent
是将按钮功能继承到图像控件的简便方法之一。 IsHitTestVisible=False
使Image控件不触发click事件。 您可以尝试下面的代码段吗
<my:NewButton Command="{Binding ToolBarCommand}" CommandParameter="Play">
<my:NewButton.Template>
<ControlTemplate TargetType="{x:Type my:NewButton}">
<StackPanel>
<Image Source="{Binding PlayState}"/>
<ContentPresenter/>
</StackPanel>
</ControlTemplate>
</my:NewButton.Template>
</my:NewButton>
如果在Image上设置IsHitTestVisible="False"
,则该按钮将不可单击,除非它后面有其他东西可以看到单击(例如XAMeLi答案中的透明Border)。 但是当IsHitTestVisible为true(默认设置)时,它应该是。 在以下示例中,即使图像是透明的,也会触发Click事件:
<Button Click="Button_Click">
<Button.Template>
<ControlTemplate TargetType="Button">
<ContentPresenter RecognizesAccessKey="True" />
</ControlTemplate>
</Button.Template>
<Image Source="..." />
</Button>
因此,如果这对您不起作用,我认为您的NewButton
类肯定发生了一些奇怪的事情。
如果我理解正确,则希望将按钮的可单击区域设置为图像的非透明区域。
设置IsHitTestVisible
将使整个图像元素不可单击,而不仅仅是透明区域。 这对您有帮助的唯一方法是,如果图像后面有透明的形状来捕获点击。
至于使用图像本身,我认为WPF对此没有任何内置支持。 您可以使用Window.AllowsTransparency这样定义整个窗口的形状,但这对您没有帮助。
您将需要通过覆盖要成形的图像元素上的HitTestCore来手动实现命中测试。 有一个例子在这里 ,你会怎么做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.