微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>

原文地址:https://www.jb51.cc/csharp/97907.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐