1

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?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Pspl
  • 1,398
  • 12
  • 23

3 Answers3

1

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.

John
  • 3,057
  • 1
  • 4
  • 10
0

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.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • Wow... That sounds too much for my skills, eh eh. I will give it a try though... Google, here I go... – Pspl Apr 22 '22 at 15:07
  • 1
    My.Settings support DataBindings. Handled by a BindingSource, the `CurrentItemChanged` event notifies when the value of a bound Setting changes. -- You could also use a Binding's `Format` event, which is raised when the value of an item of a bound collection needs to be formatted for presentation. Binding My.Settings, the new value of a Setting is formatted each time its value changes. – Jimi Apr 22 '22 at 15:23
0

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