WPF 利用附加屬性實現事件參數傳遞和引發

来源:https://www.cnblogs.com/T-ARF/archive/2020/05/18/12913413.html
-Advertisement-
Play Games

過程很簡單,傳遞ViewModel到附加屬性,附加屬性引發相關事件和取消事件,從而引發VM中的委托。 修正版本2 2020年5月19日 07點03分 徹底一模一樣了,和之前寫的。 不過更順了 添加內容 public class AttachModel: Animatable { public sta ...


過程很簡單,傳遞ViewModel到附加屬性,附加屬性引發相關事件和取消事件,從而引發VM中的委托。

修正版本2 2020年5月19日 07點03分

徹底一模一樣了,和之前寫的。

不過更順了

添加內容

 public class AttachModel: Animatable
    {
        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(AttachModel), new PropertyMetadata(null));

        public ICommand Command
        {
            get =>(ICommand) GetValue(CommandProperty) ;
            set => SetValue(CommandProperty, value);
        }

        public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(AttachModel), new PropertyMetadata(null));

        public object CommandParameter
        {
            get => GetValue(CommandParameterProperty);
            set => SetValue(CommandParameterProperty, value);
        }


        public static readonly DependencyProperty EventNameProperty = DependencyProperty.Register("EventName", typeof(string), typeof(AttachModel), new PropertyMetadata(null));

        public string EventName
        {
            get => GetValue(EventNameProperty).ToString();
            set => SetValue(EventNameProperty, value);
        }


        public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(object), typeof(AttachModel), new PropertyMetadata(null));


        protected override Freezable CreateInstanceCore()
        {
            
            return new AttachModel();
        }

        public object Source
        {
            get => GetValue(SourceProperty);
            set => SetValue(SourceProperty, value);
            
        }



       
        public static readonly DependencyProperty SourceNameProperty = DependencyProperty.Register("SourceName", typeof(string), typeof(AttachModel), new PropertyMetadata(null));

        public string SourceName
        {
            get => GetValue(SourceNameProperty).ToString();
            set => SetValue(SourceNameProperty, value);
        }

        public static readonly DependencyProperty PushAttachProperty = DependencyProperty.Register("PushAttach", typeof(bool), typeof(AttachModel), new PropertyMetadata(false));


        public bool PushAttach
        {
            get => (bool)GetValue(PushAttachProperty);
            set => SetValue(PushAttachProperty, value);
        }


    }
    public class Attach
    {
        private static DependencyObject ElementUI;
        private static Delegate dlg;
        private static AttachModel model;

        public static readonly DependencyProperty ViewModelDataProperty = DependencyProperty.RegisterAttached("ViewModelData", typeof(AttachModel), typeof(Attach), new PropertyMetadata(null, new PropertyChangedCallback(OnValueChanged)));

        private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (ElementUI != d)
                ElementUI = d;
            if (e.NewValue != null)
            {
                model = e.NewValue as AttachModel;
                if (model.PushAttach)
                {
                    if (model.Command != null)
                        DoAcion();
                }
                else if (dlg != null)
                {
                    UnDoAcion();
                }
            }

        }

        public static void SetViewModelData(DependencyObject d, AttachModel value) => d.SetValue(ViewModelDataProperty, value);

        public static AttachModel GetViewModelData(DependencyObject d) => (AttachModel)d.GetValue(ViewModelDataProperty);

 
        private static void UnDoAcion()
        {
            var uisource =ElementUI.GetType();
            var mothod = uisource.GetEvent(model.EventName);
            mothod.RemoveEventHandler(ElementUI, dlg);
            var getsource = model.Source.GetType();
            var sourcemothod = getsource.GetProperty(model.SourceName).GetValue(model.Source) as Action<object, EventArgs>;
            sourcemothod = null;
        }

        private static void DoAcion()
        {
            var getsource = ElementUI.GetType();
            var mothod = getsource.GetEvent(model.EventName);
            var k = Activator.CreateInstance(typeof(Attach));
            var local = k.GetType().GetMethod(nameof(EventMethod), BindingFlags.Public | BindingFlags.Instance);
            dlg = Delegate.CreateDelegate(mothod.EventHandlerType, k, local);
            mothod.AddEventHandler(ElementUI, dlg);
        }
        public void EventMethod(object sender, EventArgs e)
        {
            //var getsource = model.Source.GetType();
            //var mothod = getsource.GetProperty(model.SourceName).GetValue(model.Source) as Action<object, EventArgs>;
            //mothod?.Invoke(sender, e);
            if (model.CommandParameter != null)
                if (model.Command.CanExecute(model.CommandParameter))
                    model.Command.Execute(model.CommandParameter);
            if(model.CommandParameter==null)
                if (model.Command.CanExecute(e))
                    model.Command.Execute(e);
        }

        #region
        //public static readonly DependencyProperty EventNameProperty = DependencyProperty.RegisterAttached("EventName", typeof(string), typeof(AttachModel), new PropertyMetadata(null, new PropertyChangedCallback(OnEventNameValueChanged)));

        //public static void SetEventName(DependencyObject d, object value) => d.SetValue(EventNameProperty, value);

        //public static string GetEventName(DependencyObject d) => (string)d.GetValue(EventNameProperty);

        //private static void OnEventNameValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        //{
        //    if (!e.NewValue.Equals(EventName))
        //        EventName = e.NewValue.ToString();
        //}

        //public static readonly DependencyProperty SourceProperty = DependencyProperty.RegisterAttached("Source", typeof(object), typeof(AttachModel), new PropertyMetadata(null, new PropertyChangedCallback(OnSourceValueChanged)));

        //public static void SetSource(DependencyObject d, object value) => d.SetValue(SourceProperty, value);

        //public static object GetSource(DependencyObject d) => (object)d.GetValue(SourceProperty);

        //private static void OnSourceValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        //{
        //    if(ElementUI!=d)
        //    ElementUI = d;
        //    if(Source!=e.NewValue)
        //    Source = e.NewValue;
        //}

        //public static readonly DependencyProperty SourceNameProperty = DependencyProperty.RegisterAttached("SourceName", typeof(string), typeof(AttachModel), new PropertyMetadata(null, new PropertyChangedCallback(OnSourceNameValueChanged)));

        //private static void OnSourceNameValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        //{
        //    if(e.NewValue!=null)
        //    if (!e.NewValue.Equals(SourceName))
        //        SourceName = e.NewValue.ToString();
        //}

        //public static void SetSourceName(DependencyObject d, object value) => d.SetValue(SourceNameProperty, value);

        //public static string GetSourceName(DependencyObject d) => (string)d.GetValue(SourceNameProperty);
        #endregion
    }
    public class CommandBase : ICommand
    {
        private Action ex;
        private Action<EventArgs> ex2;
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            ex?.Invoke();
            ex2?.Invoke((EventArgs)parameter);
        }
        public CommandBase(Action action) => this.ex = action;
        public CommandBase(Action<EventArgs> action) => this.ex2 = action;
    }

 

model內部

public ICommand Click
        {
            get
            {
                return new CommandBase(new Action<EventArgs>(OnClick));
            }
        }

        private void OnClick(EventArgs obj)
        {
            MessageBox.Show(obj.ToString());
        }

xaml

 <Button Height="120" VerticalAlignment="Top" Content="click" x:Name="b1"    >
            <local:Attach.ViewModelData >
                <local:AttachModel Source="{Binding  }" Command="{Binding  Click}"  EventName="Click"  PushAttach="{Binding  ElementName=cb1,Path=IsChecked}" SourceName="OnSelect"/>
            </local:Attach.ViewModelData>
        </Button>

        <CheckBox Height="120" Content="click" x:Name="cb1" IsChecked="True" />

 

 

 

修正版本1:日期2020年5月18日 23點21分

有點像我之前寫的https://www.cnblogs.com/T-ARF/p/12594980.html

但是這個更加簡單,不用太多的屬性。沒有更多的限制

 public class AttachModel: Animatable
    {

        public static readonly DependencyProperty EventNameProperty = DependencyProperty.Register("EventName", typeof(string), typeof(AttachModel), new PropertyMetadata(null));

        public string EventName
        {
            get => GetValue(EventNameProperty).ToString();
            set => SetValue(EventNameProperty, value);
        }


        public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(object), typeof(AttachModel), new PropertyMetadata(null));


        protected override Freezable CreateInstanceCore()
        {
            return new AttachModel();
        }

        public object Source
        {
            get => GetValue(SourceProperty);
            set => SetValue(SourceProperty, value);
        }



       
        public static readonly DependencyProperty SourceNameProperty = DependencyProperty.Register("SourceName", typeof(string), typeof(AttachModel), new PropertyMetadata(null));

        public string SourceName
        {
            get => GetValue(SourceNameProperty).ToString();
            set => SetValue(SourceNameProperty, value);
        }

        public static readonly DependencyProperty PushAttachProperty = DependencyProperty.Register("PushAttach", typeof(bool), typeof(AttachModel), new PropertyMetadata(false));


        public bool PushAttach
        {
            get => (bool)GetValue(PushAttachProperty);
            set => SetValue(PushAttachProperty, value);
        }


    }
    public class Attach
    {
        private static DependencyObject ElementUI;
        private static Delegate dlg;
        private static AttachModel model;

        public static readonly DependencyProperty ViewModelDataProperty = DependencyProperty.RegisterAttached("ViewModelData", typeof(AttachModel), typeof(Attach), new PropertyMetadata(null, new PropertyChangedCallback(OnValueChanged)));

        private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (ElementUI != d)
                ElementUI = d;
            if (e.NewValue != null)
            {
                model = e.NewValue as AttachModel;
                if (model.PushAttach)
                {
                    DoAcion();
                }
                else if (dlg != null)
                {
                    UnDoAcion();
                }
            }

        }

        public static void SetViewModelData(DependencyObject d, AttachModel value) => d.SetValue(ViewModelDataProperty, value);

        public static AttachModel GetViewModelData(DependencyObject d) => (AttachModel)d.GetValue(ViewModelDataProperty);

 
        private static void UnDoAcion()
        {
            var uisource =ElementUI.GetType();
            var mothod = uisource.GetEvent(model.EventName);
            mothod.RemoveEventHandler(ElementUI, dlg);
            var getsource = model.Source.GetType();
            var sourcemothod = getsource.GetProperty(model.SourceName).GetValue(model.Source) as Action<object, EventArgs>;
            sourcemothod = null;
        }

        private static void DoAcion()
        {
            var getsource = ElementUI.GetType();
            var mothod = getsource.GetEvent(model.EventName);
            var k = Activator.CreateInstance(typeof(Attach));
            var local = k.GetType().GetMethod(nameof(EventMethod), BindingFlags.Public | BindingFlags.Instance);
            dlg = Delegate.CreateDelegate(mothod.EventHandlerType, k, local);
            mothod.AddEventHandler(ElementUI, dlg);
        }
        public void EventMethod(object sender, EventArgs e)
        {
            var getsource = model.Source.GetType();
            var mothod = getsource.GetProperty(model.SourceName).GetValue(model.Source) as Action<object, EventArgs>;
            mothod?.Invoke(sender, e);

        }

  
    }

XAML代碼

此處source綁定的是datacontext

    <Button Height="120" VerticalAlignment="Top" Content="click" x:Name="b1"    >
            <local:Attach.ViewModelData >
                <local:AttachModel Source="{Binding  }" EventName="Click"  PushAttach="{Binding  ElementName=cb1,Path=IsChecked}" SourceName="OnSelect"/>
            </local:Attach.ViewModelData>
        </Button>

        <CheckBox Height="120" Content="click" x:Name="cb1" IsChecked="True" />

 

 

***************************老版本*******************************************

  public class Attach
    {
        private static DependencyObject ElementUI;
        private static object Source;
        private static string SourceName;
        private static string EventName;
        private static Delegate dlg;

        public static readonly DependencyProperty EventNameProperty = DependencyProperty.RegisterAttached("EventName", typeof(string), typeof(Attach), new PropertyMetadata(null, new PropertyChangedCallback(OnEventNameValueChanged)));

        public static void SetEventName(DependencyObject d, object value) => d.SetValue(EventNameProperty, value);

        public static string GetEventName(DependencyObject d) => (string)d.GetValue(EventNameProperty);

        private static void OnEventNameValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (!e.NewValue.Equals(EventName))
                EventName = e.NewValue.ToString();
        }

        public static readonly DependencyProperty PushAttachProperty = DependencyProperty.RegisterAttached("PushAttach", typeof(bool), typeof(Attach), new PropertyMetadata(false, new PropertyChangedCallback(OnPushAttachValueChanged)));

        public static void SetPushAttach(DependencyObject d, bool value) => d.SetValue(PushAttachProperty, value);

        public static bool GetPushAttach(DependencyObject d) => (bool)d.GetValue(PushAttachProperty);
         

        private static void OnPushAttachValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue == true)
                DoAcion();
            if ((bool)e.NewValue == false)
                UnDoAcion();
        }
    
        
        private  static void UnDoAcion()
        {
            var uisource = ElementUI.GetType();
            var mothod = uisource.GetEvent(EventName);
            mothod.RemoveEventHandler(ElementUI, dlg);
            var getsource = Source.GetType();
            var sourcemothod = getsource.GetProperty(SourceName).GetValue(Source) as Action<object, EventArgs>;
            sourcemothod = null;
        }
        private static void DoAcion()
        {
            var getsource = ElementUI.GetType();
            var mothod = getsource.GetEvent(EventName);
            var k = Activator.CreateInstance(typeof(Attach));
            var local = k.GetType().GetMethod(nameof(EventMethod),BindingFlags.Public|BindingFlags.Instance);
             dlg = Delegate.CreateDelegate(mothod.EventHandlerType, k, local);
            mothod.AddEventHandler(ElementUI, dlg);
        }

        public  void EventMethod(object sender, EventArgs e)
        {
            var getsource = Source.GetType();
            var mothod = getsource.GetProperty(SourceName).GetValue(Source) as Action<object, EventArgs>;
            mothod?.Invoke(sender, e);
           
        }
        public static readonly DependencyProperty SourceProperty = DependencyProperty.RegisterAttached("Source", typeof(object), typeof(Attach), new PropertyMetadata(null, new PropertyChangedCallback(OnSourceValueChanged)));

        public static void SetSource(DependencyObject d, object value) => d.SetValue(SourceProperty, value);

        public static object GetSource(DependencyObject d) => (object)d.GetValue(SourceProperty);

        private static void OnSourceValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if(ElementUI!=d)
            ElementUI = d;
            if(Source!=e.NewValue)
            Source = e.NewValue;
        }

        public static readonly DependencyProperty SourceNameProperty = DependencyProperty.RegisterAttached("SourceName", typeof(string), typeof(Attach), new PropertyMetadata(null, new PropertyChangedCallback(OnSourceNameValueChanged)));

        private static void OnSourceNameValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if(e.NewValue!=null)
            if (!e.NewValue.Equals(SourceName))
                SourceName = e.NewValue.ToString();
        }

        public static void SetSourceName(DependencyObject d, object value) => d.SetValue(SourceNameProperty, value);

        public static string GetSourceName(DependencyObject d) => (string)d.GetValue(SourceNameProperty);

    }

 

xaml

<Button Height="120" VerticalAlignment="Top" Content="click" x:Name="b1"  local:Attach.Source="{Binding RelativeSource={RelativeSource Mode=Self},Path=DataContext}"  local:Attach.EventName="Click" local:Attach.SourceName="OnEvent" local:Attach.PushAttach="{Binding ElementName=cb1,Path=IsChecked}"/>
<CheckBox Height="120" Content="click" x:Name="cb1" IsChecked="False" />

 

ViewMode中放置一個委托即可

    public class VMTest: INotifyPropertyChanged
    {
        protected void OnValueChanged(string Name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Name));
        public event PropertyChangedEventHandler PropertyChanged;
     
        public Action<Object,EventArgs> OnEvent { get; set; }
        public VMTest()
        {
           OnEvent =new  Action<Object,EventArgs>(OnEvent);
        }
        private void OnEvent(object arg1, EventArgs arg2)
        {
            MessageBox.Show("click");
        }
    }

 

 

 

效果圖


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 前言: 這篇文章不是像評論區的某些大佬所想的那樣是來炫技的,更多的是來給大家科普一些實用的滲透工具和方法,我相信不是所在的人都用過文中提到的這些方法。 很多人學習python,不知道從何學起。很多人學習python,掌握了基本語法過後,不知道在哪裡尋找案例上手。很多已經做案例的人,卻不知道如何去學習 ...
  • 前言 本文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯繫我們以作處理。 項目背景 網上PDF轉換工具眼花繚亂,選擇困難症,有些甚至還收費; 直接以其他格式打開PDF效果一般較差; 有些小可愛通過複製粘貼的方式進行操作,浪費了大量的時間。 那麼,有 ...
  • 微信機器人的實現有三種:web,app和exe。其中web很多賬號受限登錄不了,而hook app的話需要使用xposed則會封號,所以現在大部分機器人都是基於PC微信。 先實現一下最基本的機器人的功能:接收消息和發送消息。找相關call請看:https://blog.csdn.net/qq_384 ...
  • 我看到 "這篇文章" 之後自己嘗試了一下還是找不到對應的call,畢竟沒有學習過逆向,只是因為一時興起想逆向一下微信。 找到關鍵CALL 不過我找到了一個投機取巧的辦法:因為已經知道了微信的二維碼圖片是PNG格式的,而PNG有一個通用的文件頭,如下 我們可以利用這個找到記憶體中的二維碼圖片,然後對它下 ...
  • 目標:在win10系統上安裝linux虛擬機,並ssh登陸。 第一步:安裝虛擬機 在實際工作中,通常需要多台伺服器,這時候通過虛擬軟體,將一臺主機分割模擬成多個伺服器是很好的選擇。 在這裡我使用VirtualBox虛擬軟體來創建虛擬機,官方網址:https://www.virtualbox.org/ ...
  • ​ 如果想看更多技術好書,可以關註微信公眾號【程式員書單】作者黃小斜,目前是阿裡Java工程師,業餘時間廣泛讀書,在公眾號里除了分享程式員必讀的技術書籍之外,也會推薦很多關於個人成長、投資理財等方面的書籍。你煩惱的每個問題,書中都有答案。 在這裡,我們將為你推薦幫助程式員以及互聯網從業者自我提升的各 ...
  • 啟言:每個函數定義都有鏈接器可識別的獨一無二的編譯後的函數名稱 種類:C 語言鏈接性、C++ 語言鏈接性,可能有如下的編譯器翻譯 spiff( int ) _spiff // C spiff( int ) _spiff_i // C++ (函數重載) spiff(double, double) _s ...
  • SunnyUI.Net, 基於 C# .Net WinForm 開源控制項庫、工具類庫、擴展類庫、多頁面開發框架 Blog: https://www.cnblogs.com/yhuse Gitee: https://gitee.com/yhuse/SunnyUI GitHub: https://git ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...