簡體   English   中英

C#所有WPF控件在Windows窗體中使用公共事件

[英]C# All WPF controls using a common event in Windows Form

我創建了一個這樣的自定義WPF控件:

自定義WPF按鈕

我將此WPF控件放置在Form1(Windows窗體)中,並為其編寫了一個事件MouseEnter。 我在這里期望得到的是WPF控件中按鈕的名稱。 我在Form1中僅用1個WPF控件完成了此操作。 但是我在Form1中有24個WPF控件。 我用foreach遍歷了所有ElementHost (WPF控件),並將每個ElementHost的子對象強制轉換為WPF控件。 我在將ElementHost強制轉換為WPF控件時遇到問題。

這是我的代碼:

   public Form1()
        {
            InitializeComponent();
            foreach (ElementHost c in this.Controls)
            {        

                     TP1WPFControls.TP1CustomButton bt = c.Child as TP1CustomButton;

                    bt.bt.MouseEnter += Bt_MouseEnter;    
                    bt.bt.MouseLeave += Bt_MouseLeave;
            }

            //TP1WPFControls.TP1CustomButton btnCustom = elementHost1.Child as TP1CustomButton;
            //btnCustom.bt.Click += Bt_Click;
            //btnCustom.bt.MouseEnter += Bt_MouseEnter; ;
            //btnCustom.bt.MouseLeave += Bt_MouseLeave; ;

        }

這是我的圖片,用於顯示Form1中的WPF控件: 在此處輸入圖片說明

希望大家能給我一個解決方案。

謝謝!

您需要遍歷表單控件,但並非所有控件都是元素宿主:

每個Windows Forms控件都基於System.Windows.Forms.Control(包括ElementHost)。 因此,在循環中,您嘗試強制轉換。 如果它不為null,則知道其為ElementHost,然后可以在ElementHost上執行代碼。

foreach (System.Windows.Forms.Control e in this.Controls)
{        

    ElementHost c= e as ElementHost;
    if ( c != null ) 
    {
        TP1WPFControls.TP1CustomButton bt = c.Child as TP1CustomButton;
        if ( bt != null )
        {
                // Add Events (I'd assume it would just be bt.MouseEnter but I don't know what your control looks like)
                bt.bt.MouseEnter += Bt_MouseEnter;    
                bt.bt.MouseLeave += Bt_MouseLeave;
        }
    }
}

非常感謝@ Ctznkane525。 我試圖將MouseLeave和MouseEnter事件中的發送方轉換為WPF自定義控件中每個控件的類型,並且它已經起作用了! 因為我的TPCustomButton只是一個WPF控件,所以我必須為上面的每個事件將每個控件都強制轉換為WPF控件。

我已經編輯了答案以獲取完整信息:

 public Form1()
        {
            InitializeComponent();
            foreach (Control c in this.Controls)
            {
                ElementHost e = c as ElementHost;
                if (e != null)
                {

                    TP1WPFControls.TP1CustomButton btWPF = e.Child as TP1CustomButton;
                    if (btWPF != null)
                    {

                        //bt.bt.MouseLeave += Bt_MouseLeave;
                        //bt.lbl.MouseLeave += Lbl_MouseLeave;
                        btWPF.MouseLeave += Bt_MouseLeave;
                    }
                }
            }


        }
   private void Bt_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            TP1CustomButton btCustom = sender as TP1CustomButton;


            brushcolor = new brushColor(mediaColor.FromRgb(221, 247, 190));
            btCustom.bt.Background = brushcolor;
            btCustom.lbl.Background = brushcolor;

        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM