点击事件的WPF图像控制

我希望在我的WPF应用程序中使用<Image>响应鼠标点击。 只有“鼠标向上”和“下注”事件可用于开箱即用。 我觉得这很特别。 有没有办法扩大控制或使用另一种控制方法来给出相同的效果?

为了扩展Shawn Mclean的答案,WPF的一个强大function就是能够充分利用控件的行为,同时彻底改变控件的外观。 如果你想创build一个像一个button一样的行为的图像(完成点击事件,命令绑定,默认button分配等),您可以将图像放置在button控件中,然后重新启动该button以移除button“chrome”。 这将给你一个button的漂亮的API与你的愿望。 您可以重复使用这种风格,如果您有命令绑定到新的图像button,则此方法将减less在您的代码中创build事件处理程序的需要。

创build这样的风格非常简单。 只需在资源中使用命名键创build一个新的样式资源,并将此资源分配给button的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。 无论如何,您无法选中或关注图片控件,因此只能点击图片。

另一个select是将图像放在一个button中,通过编辑控件模板来删除所有的样式,这样看起来就像一个图像。 这样,你可以使用键盘专注于它。

您可以使用一组4个处理程序和2个布尔variables:

布尔值:

  1. IsClicked
  2. IsEntered

处理:

  1. OnMouseDown-设置IsClicked为true;
  2. OnMouseEnter-sets IsEntered true;
  3. OnMouseLeave – 设置IsEntered为false;
  4. OnMouseUp – if(IsClicked && IsEntered){/ TODO your logic /}然后设置IsClicked为false;

这种结构实现了经典点击的function。

  1. OnMouseLeave – 也设置isClicked为false; 否则,您可以点击鼠标并释放鼠标。 然后点击鼠标hover,释放鼠标仍然发生点击。