单击"WPF图像的事件"

The*_*ere 9 .net c# wpf events winforms

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

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

CJK*_*CJK 20

只需将MouseDown事件添加到您的图像中即可

<Image x:Name=aPicture Source="mypic.jpg" MouseDown="aPicture_MouseDown"/>
Run Code Online (Sandbox Code Playgroud)

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

private void aPicture_MouseDown(object sender, MouseEventArgs e)
{
   //do something here
}
Run Code Online (Sandbox Code Playgroud)

  • 我建议 MouseLeftButtonDown 是更接近的等价物,但这绝对应该是公认的答案。 (3认同)

dko*_*ozl 11

在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>
Run Code Online (Sandbox Code Playgroud)

用上面的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));
   }    
}
Run Code Online (Sandbox Code Playgroud)

在XAML中:

<Button Style="{StaticResource ImageButtonStyle}" Click="ImageButton_Click" Width="..." Height="...">
    <Image Source="{Binding MyImageSource}"/>
</Button>
Run Code Online (Sandbox Code Playgroud)

  • 另外,由于他使用的是WPF,因此如果他使用MVVM而不是Click事件使用Command,则可能会更好。但这取决于他想要实现的目标。他说,点击确实做了一些重要的事情,因此,Command可能更适合。 (2认同)