来自 Settings.settings 变量的 WPF 触发器

WPF trigger from Settings.settings variable

我将 bool 变量添加到我的 Settings.settings 文件中以存储用户配置首选项:

在后面的代码中,我正在以这种方式进行更改:

Properties.Settings.Default.autoCheckForUpdates = true;

是否可以使用 XAML 将此 bool 变量添加到我的控件 trigger 中?

下面显示的 DataTrigger 有效。您不需要带有 属性 更改通知的视图模型,因为 Settings class 已经实现了 INotifyPropertyChanged。

xmlns:properties="clr-namespace:YourAppNamespace.Properties"
...

<DataTrigger Binding="{Binding Path=(properties:Settings.Default).autoCheckForUpdates}"
             Value="True">
    <Setter .../>
</DataTrigger>

正如所承诺的那样,矫枉过正的版本对您的问题没有意义,但可能会以另一种方式帮助您解决问题:带有 INotifyPropertyChanged 的​​简单视图模型。 我将使用一些绑定扩展示例。

您的视图模型:

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}"/>