c# – 单击WPF图像的事件

我正在将一个旧的WinForms桌面应用程序移植到 WPF.应用程序GUI使用WinForm的PictureBox显示图像.旧的WinForms应用程序还为所有PictureBox提供了OnClick事件处理程序.单击图像实际上做了一些重要的事情.现在我在WPF中重新编写UI,我发现按照 this,WinForm的PictureBox控件的等价物是WPF的Image.但是,当我打开WPF图像的属性面板时,没有要处理的单击事件,所以我无法像在WinForms中那样编写单击事件处理程序.

那么,请问您能告诉我如何实现相当于WinForm的PictureBox及其在WPF中的点击事件?我想在每次用户点击图像时显示图像并处理案例.

解决方法

在WPF中,每个控件都有其认模板(它的外观),但您可以轻松更改这些模板并使控件看起来像您想要的那样.这样可以更轻松地通过其功能选择控件并使其看起来像您想要的那样.在您的情况下,您需要单击,以便您选择按钮并更改其模板
<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>

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...