加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 单击WPF图像的事件

发布时间:2020-12-15 18:14:30 所属栏目:百科 来源:网络整理
导读:我正在将一个旧的WinForms桌面应用程序移植到 WPF.应用程序GUI使用WinForm的PictureBox来显示图像.旧的WinForms应用程序还为所有PictureBox提供了OnClick事件处理程序.单击图像实际上做了一些重要的事情.现在我在WPF中重新编写UI,我发现按照 this,WinForm的P
我正在将一个旧的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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读