vb.netevent-handlingmy.settings

Add an event handler to a my.settings value


I want to invoke a method every time a value from My.Settings is changed. Something like:

Private Sub myValue_Changed(sender As Object, e As EventArgs) Handles myValue.Changed
    
    (...)
    
End Sub

I know that, if I wanted to do it with a variable, I have to make it a class and set the event on it. But I can´t do it with the value from My.Settings.

Is there any way to do this?


Solution

  • As suggested in the comments on another answer, you can receive notification of a change in a setting via a Binding. Alternatively, you can do essentially what the Binding class does yourself, as there's not really all that much to it, e.g.

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim settingsPropertyDescriptors = TypeDescriptor.GetProperties(My.Settings)
        Dim setting1PropertyDescriptor = settingsPropertyDescriptors(NameOf(My.Settings.Setting1))
    
        setting1PropertyDescriptor.AddValueChanged(My.Settings, AddressOf Settings_Setting1Changed)
    End Sub
    
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        My.Settings.Setting1 = "Hello World"
    End Sub
    
    Private Sub Settings_Setting1Changed(sender As Object, e As EventArgs)
        Debug.WriteLine($"{NameOf(My.Settings.Setting1)} changed to ""{My.Settings.Setting1}""")
    End Sub
    

    This code adds a changed handler to the property via a PropertyDescriptor, just as the Binding class does.