Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Use an event from a FrameworkElement when the type of this one is unknowed

$
0
0

Hello,

I have created a Custom Control which is used as Content of a ContentControl.

I want to use an Event from his parent like this:

public class IconText : Control
{
public override void OnApplyTemplate()
{
FrameworkElement gParent = this.Parent as FrameworkElement;
gParent.MouseEnter += Control_MouseEnter;
gParent.MouseLeave += Control_MouseLeave;

// I get the gEventInfo to check whether the Event exist or not
EventInfo gEventInfo = gParent.GetType().GetEvent("Checked", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (gEventInfo != null)
{
// Iwant to use something like:
gParent.Checked += Control_Checked;

// or :
this.Checked += Control_Checked; //If the parent is checked

}
}
. . .
}

Thank you in advance.

-- Solved --

        public override void OnApplyTemplate()
        {
            gParent = this.Parent as FrameworkElement;
            gParent.MouseEnter += Control_MouseEnter;
            gParent.MouseLeave += Control_MouseLeave;


            EventInfo gEventInfo = gParent.GetType().GetEvent("Checked", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            if (gEventInfo != null)
            {
                RoutedEventHandler gEventH = Control_Checked;

                Delegate gDelegate = Delegate.CreateDelegate(gEventInfo.EventHandlerType, gEventH.Target, gEventH.Method);
                gEventInfo.AddEventHandler(gParent, gDelegate);
            }
        }
        private void Control_Checked(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("I got it!");
        }


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>