0

I added bool variable into my Settings.settings file to store user configuration preferences:

enter image description here

And in code behind i am changing this this way:

Properties.Settings.Default.autoCheckForUpdates = true;

Is it possible to add this bool var to my control trigger using XAML ?

Stefan
  • 17,448
  • 11
  • 60
  • 79
user2908206
  • 265
  • 3
  • 16
  • I would recommend using a model in between, see: https://stackoverflow.com/questions/23648832/viewmodels-in-mvc-mvvm-seperation-of-layers-best-practices – Stefan Mar 04 '18 at 08:39
  • Do you mean to use binding object with properties ? – user2908206 Mar 04 '18 at 08:47
  • Yes, create a `viewmodel` for your `xaml-view`, you can set the `BindingContext` from it's "code-behind". If your view interacts with your viewmodel, you can set your settings though that. It seems ike more effort but in the long run it is better to maintain. I could fix you an example if you like – Stefan Mar 04 '18 at 08:52
  • Yes i will glad to see example, BTW i need to implement INotifyPropertyChanged as well ? – user2908206 Mar 04 '18 at 08:56

2 Answers2

3

The DataTrigger shown below works. You don't need a view model with property change notification, since the Settings class already implements INotifyPropertyChanged.

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

<DataTrigger Binding="{Binding Path=(properties:Settings.Default).autoCheckForUpdates}"
             Value="True">
    <Setter .../>
</DataTrigger>
Clemens
  • 123,504
  • 12
  • 155
  • 268
1

As promised, the overkill version, which doesn't makes sense for your question but might help you out in another way: a simple viewmodel with INotifyPropertyChanged. I wil extend the example with some binding.

Your 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));
    }
}    

In the code behind of your XAML:

public SettingsWindow()
{
    InitializeComponent();
    this.DataContext = new SettingsViewModel();
}

Now, in your XAML, you can bind to this property, through a textbox for example:

<CheckBox IsChecked="{Binding AutoCheckForUpdates}"/>
Stefan
  • 17,448
  • 11
  • 60
  • 79