.NET Custom Settings Event Handlers

I am trying to use the built-in parameters of a .NET application. So, for example, I have a custom year parameter.

If the end user changes the setting in the program, I need to respond by updating the displayed data.

Currently, the following code is used for this:

Settings.Default.PropertyChanged += SettingsChanged; //on year change clear out the grid and update the data private void SettingsChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == "year") { grdStudentCourseSearch.DataSource = null; grdStudentCourseSearch.DataMember = null; UpdateData(); } } 

As you can see, they only seem to have an event handler for all parameters, and I need to use e.PropertyName to compare the strings to see which property has changed. Is there a better way to do this? Potentially, if I later change the names of the properties, this could be forgotten.

+4
source share
5 answers

I believe that there is no better way (using the generated settings class) due to the implementation of the settings class. Consider the generated class code for a simple line:

 public string Test { get { return ((string)(this["Test"])); } set { this["Test"] = value; } } 

As you can see, it uses an indexer with a string value - you do not have a specialized TestChanged event or some of them. The OnPropertyChanged call OnPropertyChanged made in the indexer installer:

 set { SettingChangingEventArgs e = new SettingChangingEventArgs(propertyName, base.GetType().FullName, this.SettingsKey, value, false); this.OnSettingChanging(this, e); if (!e.Cancel) { base[propertyName] = value; PropertyChangedEventArgs args2 = new PropertyChangedEventArgs(propertyName); this.OnPropertyChanged(this, args2); } } 
+1
source

You can implement settings like this:

 class Settings { public event EventHandler YearChanged; private int _year; public int Year { get { return _year; } set { if (_year != value) { _year = value; OnYearChanged(EventArgs.Empty); } } } protected virtual void OnYearChanged(EventArgs e) { if (YearChanged != null) YearChanged(this, e); } } 

You can then register for the YearChanged event.

+1
source

No, this is not a good idea. The code is too fragile. Catch it before. For example, at the user interface level, whatever code you have, sets the value of the parameter. He can trigger an event, and you will know exactly what has changed. Or make an intermediate helper class.

+1
source

In an earlier .net structure (3.5, I think) we can use the nameof keyword to avoid magic strings, therefore e.PropertyChange == nameof (Year). Thus, you will be warned by the compiler when the property identifier has changed.

+1
source

You can simply create a variable and assign it the current settings at runtime, and then simply update one variable when it changes, after comparing it with the previous one.

0
source

All Articles