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?
CodePudding user response:
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
.
CodePudding user response:
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.