Add an event handler to a my.settings value

237 views Asked by At

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?

3

There are 3 answers

0
John On BEST ANSWER

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.

2
Joel Coehoorn On

In a word: no. My.Settings doesn't support this on it's own.

What you can do is make your own class that wraps My.Settings. As long as you use this new class, and never go to My.Settings directly any more, then you can put an event on that class which will do what you need.

However, even here, there's no way to enforce the use of the new class, and prevent direct access to My.Settings.

0
Brendan Ray On

Are you looking for something like this? ApplicationSettingsBase.SettingChanging Event

Partial Friend NotInheritable Class MySettings
    Inherits Configuration.ApplicationSettingsBase
    Private Sub MySettings_SettingChanging(sender As Object, e As System.Configuration.SettingChangingEventArgs) Handles Me.SettingChanging
        If e.SettingName.Equals(NameOf(My.Settings.Setting1)) Then
            'Do Stuff
        End If
    End Sub
End Class