首页 > 其他分享 >WPF MouseWheel MouseDown MouseUp MouseMove mapped in mvvm via behavior

WPF MouseWheel MouseDown MouseUp MouseMove mapped in mvvm via behavior

时间:2024-07-09 11:42:23浏览次数:14  
标签:via MouseWheel mvvm image System var using null public

//xaml
<Window x:Class="WpfApp201.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:local="clr-namespace:WpfApp201"
        mc:Ignorable="d" WindowState="Maximized"
        Title="{Binding MainTitle,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
        Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ListBox x:Name="lbx" Grid.Column="0"                  
                 ItemsSource="{Binding BooksList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 SelectedIndex="{Binding SelectedIdx,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 SelectedItem="{Binding SelectedBook,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Image Source="{Binding ImgUrl}" Width="200" Height="500" 
                           RenderOptions.BitmapScalingMode="LowQuality"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Image x:Name="img" Grid.Column="1" Source="{Binding SelectedItem.ImgUrl,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,ElementName=lbx}"
               ClipToBounds="True">
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="MouseWheel">
                    <behavior:CallMethodAction TargetObject="{Binding}" MethodName="Image_MouseWheel"/>
                </behavior:EventTrigger>
                <behavior:EventTrigger EventName="MouseDown">
                    <behavior:CallMethodAction TargetObject="{Binding}" MethodName="img_MouseDown"/>
                </behavior:EventTrigger>
                <behavior:EventTrigger EventName="MouseUp">
                    <behavior:CallMethodAction TargetObject="{Binding}" MethodName="img_MouseUp"/>
                </behavior:EventTrigger>
                <behavior:EventTrigger EventName="MouseMove">
                    <behavior:CallMethodAction TargetObject="{Binding}" MethodName="img_MouseMove"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
            <Image.RenderTransform>
                <TransformGroup>
                    <ScaleTransform />
                    <TranslateTransform />
                </TransformGroup>
            </Image.RenderTransform>
        </Image>
    </Grid>
</Window>


//cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace WpfApp201
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new BookVM();
            this.DataContext = vm;
        }
    }

    public class BookVM : INotifyPropertyChanged
    {
        public BookVM()
        {
            InitData();
            InitTimer();
        }

        private void InitTimer()
        {
            System.Timers.Timer tm = new System.Timers.Timer();
            tm.Elapsed += Tm_Elapsed;
            tm.Interval = 100;
            //tm.Start();
        }

        private void Tm_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (++SelectedIdx >= BooksList.Count)
            {
                SelectedIdx = 0;
            }
        }

        private void InitData()
        {
            var imgsList = Directory.GetFiles(@"..\..\Images");
            if (imgsList != null && imgsList.Any())
            {
                BooksList = new List<Book>();
                int len = imgsList.Count();
                for (int i = 0; i < 100000; i++)
                {
                    BooksList.Add(new Book()
                    {
                        Id = i + 1,
                        ImgUrl = imgsList[i % len]
                    });
                }
                SelectedBook = BooksList[0];
            }
        }

        public void img_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var image = sender as Image;
            if (image != null)
            {
                CurrentPt = e.GetPosition(image);
            }
        }

        public void img_MouseUp(object sender, MouseButtonEventArgs e)
        {
            var image = sender as Image;
            if (image != null && isMoving && e.ChangedButton == MouseButton.Left && e.ButtonState == MouseButtonState.Released)
            {
                var transformGroup = image.RenderTransform as TransformGroup;
                if (transformGroup != null)
                {
                    foreach (var child in transformGroup.Children)
                    {
                        var translater = child as TranslateTransform;
                        if (translater != null)
                        {
                            var pt = e.GetPosition(image);
                            translater.X += pt.X - CurrentPt.X;
                            translater.Y += pt.Y - CurrentPt.Y;
                            break;
                        } 
                    }
                }
            }
        }

        public void img_MouseMove(object sender, MouseEventArgs e)
        {
            var image = sender as Image;
            if (image != null)
            {
                isMoving = true;
            }
        }

        public void Image_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            //new System.Linq.SystemCore_EnumerableDebugView<System.Windows.Media.Transform>(((System.Windows.Media.TransformGroup)image.RenderTransform).Children).Items[0]
            var image = sender as Image;
            if (image != null)
            {
                var transformGroup = image.RenderTransform as TransformGroup;
                if (transformGroup != null)
                {
                    foreach (var child in transformGroup.Children)
                    {
                        var scaler = child as ScaleTransform;
                        if (scaler != null)
                        {
                            if (e.Delta > 0)
                            {
                                scaler.ScaleX *= 1.2;
                                scaler.ScaleY *= 1.2;
                            }
                            else
                            {
                                scaler.ScaleX /= 1.2;
                                scaler.ScaleY /= 1.2;
                            }
                            scaler.CenterX = e.GetPosition(image).X;
                            scaler.CenterY = e.GetPosition(image).Y;
                            break;
                        }
                    }
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }

        private bool isMoving = false;

        private Point currentPt;
        public Point CurrentPt
        {
            get
            {
                return currentPt;
            }
            set
            {
                if (value != currentPt)
                {
                    currentPt = value;
                    OnPropertyChanged(nameof(CurrentPt));
                }
            }
        }

        private int selectedIdx;
        public int SelectedIdx
        {
            get
            {
                return selectedIdx;
            }
            set
            {
                if (value != selectedIdx)
                {
                    selectedIdx = value;
                    OnPropertyChanged(nameof(SelectedIdx));
                }
            }
        }

        private Book selectedBook;
        public Book SelectedBook
        {
            get
            {
                return selectedBook;
            }
            set
            {
                if (value != selectedBook)
                {
                    selectedBook = value;
                    OnPropertyChanged(nameof(SelectedBook));
                    MainTitle = SelectedBook?.ToString();
                }
            }
        }

        private List<Book> booksList;
        public List<Book> BooksList
        {
            get
            {
                return booksList;
            }
            set
            {
                if (value != booksList)
                {
                    booksList = value;
                    OnPropertyChanged(nameof(BooksList));
                }
            }
        }

        private string mainTitle;
        public string MainTitle
        {
            get
            {
                return mainTitle;
            }
            set
            {
                mainTitle = value;
                OnPropertyChanged(nameof(MainTitle));
            }
        }
    }

    public class Book
    {
        public int Id { get; set; }

        public string ImgUrl { get; set; }

        public override string ToString()
        {
            return $"{Id},{System.IO.Path.GetFullPath(ImgUrl)}";
        }
    }

}

 

 

Key part

<Image x:Name="img" Grid.Column="1" Source="{Binding SelectedItem.ImgUrl,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,ElementName=lbx}"
       ClipToBounds="True">
    <behavior:Interaction.Triggers>
        <behavior:EventTrigger EventName="MouseWheel">
            <behavior:CallMethodAction TargetObject="{Binding}" MethodName="Image_MouseWheel"/>
        </behavior:EventTrigger>
        <behavior:EventTrigger EventName="MouseDown">
            <behavior:CallMethodAction TargetObject="{Binding}" MethodName="img_MouseDown"/>
        </behavior:EventTrigger>
        <behavior:EventTrigger EventName="MouseUp">
            <behavior:CallMethodAction TargetObject="{Binding}" MethodName="img_MouseUp"/>
        </behavior:EventTrigger>
        <behavior:EventTrigger EventName="MouseMove">
            <behavior:CallMethodAction TargetObject="{Binding}" MethodName="img_MouseMove"/>
        </behavior:EventTrigger>
    </behavior:Interaction.Triggers>
    <Image.RenderTransform>
        <TransformGroup>
            <ScaleTransform />
            <TranslateTransform />
        </TransformGroup>
    </Image.RenderTransform>
</Image>

 

 

  public void img_MouseDown(object sender, MouseButtonEventArgs e)
  {
      var image = sender as Image;
      if (image != null)
      {
          CurrentPt = e.GetPosition(image);
      }
  }

  public void img_MouseUp(object sender, MouseButtonEventArgs e)
  {
      var image = sender as Image;
      if (image != null && isMoving && e.ChangedButton == MouseButton.Left && e.ButtonState == MouseButtonState.Released)
      {
          var transformGroup = image.RenderTransform as TransformGroup;
          if (transformGroup != null)
          {
              foreach (var child in transformGroup.Children)
              {
                  var translater = child as TranslateTransform;
                  if (translater != null)
                  {
                      var pt = e.GetPosition(image);
                      translater.X += pt.X - CurrentPt.X;
                      translater.Y += pt.Y - CurrentPt.Y;
                      break;
                  } 
              }
          }
      }
  }

  public void img_MouseMove(object sender, MouseEventArgs e)
  {
      var image = sender as Image;
      if (image != null)
      {
          isMoving = true;
      }
  }

  public void Image_MouseWheel(object sender, MouseWheelEventArgs e)
  {
      //new System.Linq.SystemCore_EnumerableDebugView<System.Windows.Media.Transform>(((System.Windows.Media.TransformGroup)image.RenderTransform).Children).Items[0]
      var image = sender as Image;
      if (image != null)
      {
          var transformGroup = image.RenderTransform as TransformGroup;
          if (transformGroup != null)
          {
              foreach (var child in transformGroup.Children)
              {
                  var scaler = child as ScaleTransform;
                  if (scaler != null)
                  {
                      if (e.Delta > 0)
                      {
                          scaler.ScaleX *= 1.2;
                          scaler.ScaleY *= 1.2;
                      }
                      else
                      {
                          scaler.ScaleX /= 1.2;
                          scaler.ScaleY /= 1.2;
                      }
                      scaler.CenterX = e.GetPosition(image).X;
                      scaler.CenterY = e.GetPosition(image).Y;
                      break;
                  }
              }
          }
      }
  }

 

 

 

 

 

 

 

 

 

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Windows;

namespace Microsoft.Xaml.Behaviors.Core;

public class CallMethodAction : TriggerAction<DependencyObject>
{
    private class MethodDescriptor
    {
        public MethodInfo MethodInfo { get; private set; }

        public bool HasParameters => Parameters.Length != 0;

        public int ParameterCount => Parameters.Length;

        public ParameterInfo[] Parameters { get; private set; }

        public Type SecondParameterType
        {
            get
            {
                if (Parameters.Length >= 2)
                {
                    return Parameters[1].ParameterType;
                }
                return null;
            }
        }

        public MethodDescriptor(MethodInfo methodInfo, ParameterInfo[] methodParams)
        {
            MethodInfo = methodInfo;
            Parameters = methodParams;
        }
    }

    private List<MethodDescriptor> methodDescriptors;

    public static readonly DependencyProperty TargetObjectProperty = DependencyProperty.Register("TargetObject", typeof(object), typeof(CallMethodAction), new PropertyMetadata(OnTargetObjectChanged));

    public static readonly DependencyProperty MethodNameProperty = DependencyProperty.Register("MethodName", typeof(string), typeof(CallMethodAction), new PropertyMetadata(OnMethodNameChanged));

    public object TargetObject
    {
        get
        {
            return GetValue(TargetObjectProperty);
        }
        set
        {
            SetValue(TargetObjectProperty, value);
        }
    }

    public string MethodName
    {
        get
        {
            return (string)GetValue(MethodNameProperty);
        }
        set
        {
            SetValue(MethodNameProperty, value);
        }
    }

    private object Target => TargetObject ?? base.AssociatedObject;

    public CallMethodAction()
    {
        methodDescriptors = new List<MethodDescriptor>();
    }

    protected override void Invoke(object parameter)
    {
        if (base.AssociatedObject == null)
        {
            return;
        }
        MethodDescriptor methodDescriptor = FindBestMethod(parameter);
        if (methodDescriptor != null)
        {
            ParameterInfo[] parameters = methodDescriptor.Parameters;
            if (parameters.Length == 0)
            {
                methodDescriptor.MethodInfo.Invoke(Target, null);
            }
            else if (parameters.Length == 2 && base.AssociatedObject != null && parameter != null && parameters[0].ParameterType.IsAssignableFrom(base.AssociatedObject.GetType()) && parameters[1].ParameterType.IsAssignableFrom(parameter.GetType()))
            {
                methodDescriptor.MethodInfo.Invoke(Target, new object[2] { base.AssociatedObject, parameter });
            }
        }
        else if (TargetObject != null)
        {
            throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, ExceptionStringTable.CallMethodActionValidMethodNotFoundExceptionMessage, MethodName, TargetObject.GetType().Name));
        }
    }

    protected override void OnAttached()
    {
        base.OnAttached();
        UpdateMethodInfo();
    }

    protected override void OnDetaching()
    {
        methodDescriptors.Clear();
        base.OnDetaching();
    }

    private MethodDescriptor FindBestMethod(object parameter)
    {
        if (parameter != null)
        {
            parameter.GetType();
        }
        return methodDescriptors.FirstOrDefault((MethodDescriptor methodDescriptor) => !methodDescriptor.HasParameters || (parameter != null && methodDescriptor.SecondParameterType.IsAssignableFrom(parameter.GetType())));
    }

    private void UpdateMethodInfo()
    {
        methodDescriptors.Clear();
        if (Target == null || string.IsNullOrEmpty(MethodName))
        {
            return;
        }
        MethodInfo[] methods = Target.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public);
        foreach (MethodInfo method in methods)
        {
            if (IsMethodValid(method))
            {
                ParameterInfo[] methodParams = method.GetParameters();
                if (AreMethodParamsValid(methodParams))
                {
                    methodDescriptors.Add(new MethodDescriptor(method, methodParams));
                }
            }
        }
        methodDescriptors = methodDescriptors.OrderByDescending(delegate(MethodDescriptor methodDescriptor)
        {
            int num = 0;
            if (methodDescriptor.HasParameters)
            {
                Type type = methodDescriptor.SecondParameterType;
                while (type != typeof(EventArgs))
                {
                    num++;
                    type = type.BaseType;
                }
            }
            return methodDescriptor.ParameterCount + num;
        }).ToList();
    }

    private bool IsMethodValid(MethodInfo method)
    {
        if (!string.Equals(method.Name, MethodName, StringComparison.Ordinal))
        {
            return false;
        }
        if (method.ReturnType != typeof(void))
        {
            return false;
        }
        return true;
    }

    private static bool AreMethodParamsValid(ParameterInfo[] methodParams)
    {
        if (methodParams.Length == 2)
        {
            if (methodParams[0].ParameterType != typeof(object))
            {
                return false;
            }
            if (!typeof(EventArgs).IsAssignableFrom(methodParams[1].ParameterType))
            {
                return false;
            }
        }
        else if (methodParams.Length != 0)
        {
            return false;
        }
        return true;
    }

    private static void OnMethodNameChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        ((CallMethodAction)sender).UpdateMethodInfo();
    }

    private static void OnTargetObjectChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        ((CallMethodAction)sender).UpdateMethodInfo();
    }
}

 

标签:via,MouseWheel,mvvm,image,System,var,using,null,public
From: https://www.cnblogs.com/Fred1987/p/18291451

相关文章

  • WPF single instance via mutex
    usingSystem;usingSystem.Collections.Generic;usingSystem.Configuration;usingSystem.Data;usingSystem.Diagnostics.Eventing.Reader;usingSystem.Linq;usingSystem.Runtime.InteropServices;usingSystem.Threading;usingSystem.Threading.Tasks;usingS......
  • WPF MenuItem behavior MVVM
    //xaml<ImageGrid.Column="1"ClipToBounds="True"Source="{BindingSelectedItem.ImgUrl,ElementName=lbx}"><Image.ContextMenu><ContextMenu><MenuItemHeader="S......
  • WPF MVVM capture window keyboard
    //xaml<behavior:Interaction.Triggers><behavior:EventTriggerEventName="KeyDown"><behavior:CallMethodActionTargetObject="{Binding}"MethodName="Window_KeyDown"/></beha......
  • Towards Accurate and Robust Architectures via Neural Architecture Search
    基于网络架构搜索的准确性与鲁棒性结构研究论文链接:https://arxiv.org/abs/2405.05502项目链接:未开源Abstract为了保护深度神经网络免受对抗性攻击,对抗性训练因其有效性而受到越来越多的关注。然而,对抗训练的准确性和鲁棒性受到体系结构的限制,因为对抗训练通过调整隶属......
  • Bug记录|vivia主题|Hexo+GitHub搭建个人博客
    1.将本地SSH添加到远程github 中,之后关联远程或push出现以下错误:fatal:Notagitrepository(oranyoftheparentdirectories):.git解决方案:执行 gitinit。gitinit2.hexog无法成功运行,出现以下错误:TypeError:C:\Users\Maxence\Desktop\项目\MyBlog\Hexo......
  • WPF Image scalertransform translatetransform mvvm,custom delegate command Comman
    //xaml<Windowx:Class="WpfApp187.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mi......
  • Visual C++ generate uuid via UuidCreate and CoCreateGuid,get time now,write stri
    //ConsoleApplication3.cpp:Thisfilecontainsthe'main'function.Programexecutionbeginsandendsthere.//#pragmacomment(lib,"rpcrt4.lib")#include<windows.h>#include<chrono>#include<ctime>#include&l......
  • [论文阅读] Calligraphy Font Generation via Explicitly Modeling Location-Aware Gl
    Pretitle:CalligraphyFontGenerationviaExplicitlyModelingLocation-AwareGlyphComponentDeformationssource:TMM2023paper:https://ieeexplore.ieee.org/document/10356848code:None关键词:generativeadversarialnetworks,imageprocessing,imagesynth......
  • [HBM] HBM TSV (Through Silicon Via) 结构与工艺
    依公知及经验整理,原创保护,禁止转载。专栏《深入理解DDR》全文3300字。1概念1.1什么是HBMTSV使用TSV堆叠多个DDRDRAM成为一块HBM,成倍提高了存储器位宽,一条位宽相当于高速公路的一条车道,车道越多,在相同的车速下,传输运输量自然越大。1.2TSV优点(1)高密......
  • MODEL COMPRESSION VIA DISTILLATION AND QUANTIZATION翻译
    摘要:深度神经网络(DNNs)继续取得重大进展,解决了从图像分类到翻译或增强学习的任务。这个领域的一个受到广泛关注的方面是在资源受限环境中(如移动或嵌入式设备)高效执行深度模型。本文聚焦于这一问题,并提出了两种新的压缩方法,这两种方法共同利用了权重量化和大型网络(称为“教师”网络)......