Create custom wpf event

后端 未结 2 1059
醉酒成梦
醉酒成梦 2021-02-05 09:21

i\'ve created an UserControl for Database connection where user input Username and Password for a connection. This UserControl is in a MainWindow.xaml

Now, in code behin

相关标签:
2条回答
  • 2021-02-05 09:47

    First you should define a delegate and then use that delegate to define that event.

    In your MyUserControl.xaml.cs file add the following

    Option 1

        public delegate void MyPersonalizedUCEventHandler(string sampleParam);
    
        public event MyPersonalizedUCEventHandler MyPersonalizedUCEvent;
    
        public void RaiseMyEvent()
        {
            // Your logic
            if (MyPersonalizedUCEvent != null)
            {
                MyPersonalizedUCEvent("sample parameter");
            }
        }
    

    And that's it. You have defined your event.

    Option 2

        public event Action<String> MyPersonalizedUCEvent;
    
        public void RaiseMyEvent()
        {
            // Your logic
            if (MyPersonalizedUCEvent != null)
            {
                MyPersonalizedUCEvent("sample parameter");
            }
        }
    

    More about the Action delegate can be found in this link.

    Note:

    In many cases if events are not used properly they can cause memory leaks. Just make sure that you have written code to remove the registered event handlers as shown below.

            MyPersonalizedUCEvent -= MyPersonalizedUCEventHandler;
    
    0 讨论(0)
  • 2021-02-05 09:52

    First create a public event in your class :

    public event EventHandler<MyEventArgs> SomethingChanged;
    

    NB MyEventArgs is the type of object that will be passed with the event to subscribers. For this example it could be like this :

    public class MyEventArgs{
        public String Prop1 {get; set;}
    }
    

    Next fire it as-is in your class :

    SomethingChanged?.Invoke(this, new MyEventArgs() { Prop1="test" });
    

    Finnally handle it like this :

    private void OnSomethingChanged(object sender, MyEventArgs e)
    {
        //TODO
    }
    

    NB You need to subscribe to the event in order to enter in the OnSometingChanged method. Subscribe like this :

    myClass.SomethingChanged+=OnSomethingChanged;
    

    Where myClass is an instance of the class where you define SomethingChanged

    0 讨论(0)
提交回复
热议问题