如何使WPF中的图像控件支持左键单击和拖动操作?



我需要在WPF中显示一个浮动图像,它需要支持以下操作

  1. 用户应该能够点击图像(如一个切换按钮)。
  2. 用户应该能够拖动图像在屏幕上的任何地方。

我在窗口上使用PreviewMouseDown事件来处理拖动,并为图像控件上的左键单击创建了InputBindings来处理图像上的单击事件。

没有调用Click命令处理程序。

下面是XAML

<Window x:Class="Views.ImageControlTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Height="130" Width="224"
WindowStyle="None"
AllowsTransparency="True"
ResizeMode="NoResize"
PreviewMouseDown="Window_PreviewMouseDown">
<Window.Background>
<SolidColorBrush Opacity="0.0" Color="White"/>
</Window.Background>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="108"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<Image Grid.Row="0" Cursor="Hand" Source="{Binding ImagePath}" Height="108" Width="108">
<Image.InputBindings>
<MouseBinding Gesture="LeftClick" Command="{Binding ClickCommand, Mode=OneTime}" />
</Image.InputBindings>
</Image>

<TextBlock Grid.Row="1" Background="LightGray"  Text={Binding State} FontSize="14" Height="20" Width="224" FontFamily="Segoe UI"></TextBlock>
</Grid>

</Window>

InputBinding是一个依赖于核心WPF鼠标和键盘事件的高级API。因此,如果您在Window上处理冒泡的PreviewMouseDown,则其LeftMouseButtonDown对应将不会被原始源(Image)引发,并且不会有触发手势的事件。考虑另一种不需要处理预览事件的方法。

最新更新