0

I wrote a static class, as shown below:

namespace BkhText

{ static class Data { //自定义事件委托

    //发送信息
    public delegate void PropertyChangedEventHandler(string e);
    public static event PropertyChangedEventHandler propertyChangedHandler;

    //定义数据类型
    private static string data1;

    public static string MyProperty_data1
    {
        get
        {
            return data1;
        }
        set
        {
            data1 = value;
            propertyChangedHandler(data1);
        }
    }

}

}

When I assign a value to it somewhere else, it will prompt

        private void Button01_Click(object sender, RoutedEventArgs e)
    {  
        Data.MyProperty_data1 = "test";
    }

the object reference is not set to an instance of the object.I hope you could help me. And Thanks

ericsjz
  • 27
  • 6
  • `propertyChangedHandler` is `null` because nothing has subscribed to it. – ProgrammingLlama Jun 28 '21 at 07:24
  • See the `Events (C#)` section of [this answer](https://stackoverflow.com/a/4660186/3181933). – ProgrammingLlama Jun 28 '21 at 07:24
  • Thank you very much. I'm new hand, could you help me modify it? Thanks a lot. – ericsjz Jun 28 '21 at 07:28
  • 1
    `propertyChangedHandler?.Invoke(data1);` should do it. – ProgrammingLlama Jun 28 '21 at 07:29
  • 1
    See [here](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-) for information on what `?.` does. – ProgrammingLlama Jun 28 '21 at 07:31
  • Be aware that in order to make a static property change event work with WPF data binding, it must adhere to a naming convention. It must either be named `StaticPropertyChanged` or `MyProperty_data1Changed`. In the former case, you must not pass a string as argument, but a PropertyChangedEventArgs with the correct property name. See here for details: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/getting-started/whats-new?redirectedfrom=MSDN&view=netframeworkdesktop-4.8#binding-to-static-properties – Clemens Jun 28 '21 at 08:08

0 Answers0