繁体   English   中英

WPF 图像的单击事件

[英]Click Event for WPF Image

我正在将旧的 WinForms 桌面应用程序移植到 WPF。 应用程序 GUI 使用 WinForm 的PictureBox来显示图像。 旧的 WinForms 应用程序还具有用于所有图片框的OnClick事件处理程序。 单击图像实际上做了一些重要的事情。 现在,我重新做在WPF用户界面,我发现按照这个的等效的WinForm的PictureBox控件是WPF的Image 但是,当我打开 WPF Image的属性面板时,没有要处理的click事件,因此我无法像在 WinForms 中那样编写单击事件处理程序。

那么,你能告诉我可以做些什么来实现 WinForm 的PictureBox和它在 WPF 中的点击事件吗? 我想在每次用户单击图像时显示图像并处理案例。

只需像这样向您的图像添加一个 MouseDown(或建议的 MouseLeftButtonDown)事件

<Image x:Name=aPicture Source="mypic.jpg" MouseDown="aPicture_MouseDown"/>
// or
<Image x:Name=aPicture Source="mypic.jpg" MouseLeftButtonDown="aPicture_MouseDown"/>

这应该将它添加到您的代码后面

private void aPicture_MouseDown(object sender, MouseEventArgs e)
{
   //do something here
}

在 WPF 中,每个控件都有其默认模板(外观),但您可以轻松更改这些模板并使控件看起来像您想要的那样。 这样可以更轻松地通过其功能选择控件并使其看起来像您想要的那样。 在您的情况下,您想要Click以便选择Button并更改其Template

<Window ...>
    <Window.Resources>
        <Style TargetType="{x:Type Button}" x:Key="ImageButtonStyle">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <ContentPresenter/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Button Style="{StaticResource ImageButtonStyle}" Click="ImageButton_Click">
        <Image Source="..."/>
    </Button>
</Window>

使用上述 XAML Image将成为您的Button

编辑

您可以在下面找到如何绑定/更改Image.Source简化版本,其中一切都在 MainWindow 中完成,但基本上在 WPF 中,您不操作控件而是使用Binding绑定它们的属性并操作这些属性。 通常您会创建专用类(ViewModel)。 您的类需要实现INofityPropertyChanged接口,需要相应地设置DataContext并且每次更改其值时绑定属性需要引发INofityPropertyChanged.PropertyChanged事件(这就是您通知 UI 刷新值的方式)

public partial class MainWindow : Window, INotifyPropertyChanged
{
   public MainWindow()
   {
      InitializeComponent();
      DataContext = this;
   }

   private ImageSource _myImageSource;

   public ImageSource MyImageSource
   {
      get { return _myImageSource; }
      set
      {
          _myImageSource = value;
          OnPropertyChanged("MyImageSource");
      }
   }

   private void ImageButton_Click(object sender, RoutedEventArgs e)
   {
       this.MyImageSource = new BitmapImage(...); //you change source of the Image
   }

   public event PropertyChangedEventHandler PropertyChanged;

   private void OnPropertyChanged(string propertyName)
   {
      var handler = PropertyChanged;
      if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
   }    
}

并在 XAML 中:

<Button Style="{StaticResource ImageButtonStyle}" Click="ImageButton_Click" Width="..." Height="...">
    <Image Source="{Binding MyImageSource}"/>
</Button>

为了获得完整的可点击体验,我建议使用 CJK 方法并将 Cursor 属性设置为 Hand。

<Image x:Name="btnSearch" Source="/Images/search/search.png" MouseDown="btnSearch_MouseDown" Cursor="Hand"/>

也许MouseLeftButtonDown会更合适。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM