我希望在我的 WPF 应用程序中使用一个响应鼠标点击的 <Image>
。默认情况下,只有“Mouse Up”和“Mouse Down”事件可用,这令人感到相当特别。是否有一种扩展控件或使用另一个控件以达到相同效果的方法?
我希望在我的 WPF 应用程序中使用一个响应鼠标点击的 <Image>
。默认情况下,只有“Mouse Up”和“Mouse Down”事件可用,这令人感到相当特别。是否有一种扩展控件或使用另一个控件以达到相同效果的方法?
对Shawn Mclean的回答进行补充,WPF的一个伟大特点是能够利用控件的行为而完全改变该控件的外观。如果你想创建一个像按钮一样的图像(包括点击事件、命令绑定、默认按钮分配等),你可以将一个图片放在一个按钮控件中,并重新定义该按钮的样式以去除按钮的“边框”。这将给你所需的外观和按钮的良好API。你可以重复使用这个样式,这种方法将减少在后台代码中创建事件处理程序的需要,如果你有要绑定到新的图像按钮的命令。
创建这样的样式非常容易。只需要在资源中创建一个具有命名键的新样式资源,并将此资源分配给你的按钮的Style属性。下面是我临时拼凑的一个示例:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ButtonStyleTestApp.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Window.Resources>
<Style x:Key="NoChromeButton" TargetType="{x:Type Button}">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid x:Name="Chrome" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="#ADADAD"/>
<Setter Property="Opacity" TargetName="Chrome" Value="0.5"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid x:Name="LayoutRoot" Background="#FF44494D">
<Button Style="{DynamicResource NoChromeButton}" Click="ButtonClicked" >
<Image Source="Desert.png" Stretch="None"/>
</Button>
</Grid>
</Window>
使用MouseUp事件。你无法通过Tab键或焦点聚集在图像控件上,那就只能用这种方式来单击它。
另一种选择是将图像放入按钮中,并通过编辑控件模板删除所有样式,使其看起来像是一张图片。这样,你可以使用键盘聚焦于它。
Image
包装在Hyperlink
中,像这样:
<TextBlock>
<Hyperlink Command="{Binding VisitWebsiteCommand}"
CommandParameter="http://www.google.com"
Cursor="Hand"
TextDecorations="{x:Null}">
<Image Height="50"
Source="{StaticResource YourImageResource}"
Width="50" />
</Hyperlink>
</TextBlock>