正如承诺的那样,overkill版本对你的问题没有意义,但可能会在另一方面帮助你:一个简单的视图模型,INotifyPropertyChanged。
我将用一些绑定来扩展这个示例。
您的viewmodel:
public class SettingsViewModel : INotifyPropertyChanged
{
private bool _autoUpdate;
public SettingsViewModel()
{
//set initial value
_autoUpdate = Properties.Settings.Default.autoCheckForUpdates;
}
public bool AutoCheckForUpdates
{
get { return _autoUpdate; }
set
{
if (value == _autoUpdate) return;
_autoUpdate= value;
Properties.Settings.Default.autoCheckForUpdates = value;
Properties.Settings.Default.Save();
OnPropertyChanged();
}
}
//the INotifyPropertyChanged stuff
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
在XAML的代码背后:
public SettingsWindow()
{
InitializeComponent();
this.DataContext = new SettingsViewModel();
}
现在,在XAML中,可以通过文本框绑定到此属性,例如:
<CheckBox IsChecked="{Binding AutoCheckForUpdates}"/>