Luís Gustavo
Luís Gustavo

Reputation: 151

Update Properties.Settings binding

I have a readonly textbox in UI with is binding to Properties.Settings.Default.MyVar, when the window is open the bind correctly get the value. But when user click a button (this button change the Properties.Setting.Default.MyVar) the textbox dont update (But if I close the window and open it again then I get the new value). I already try the UpdataSourceTrigger but doesn't work.

My xml:

<TextBox IsReadOnly="True"
         Text="{Binding Source={StaticResource settings}, Path=MyVar}"/>
<Button Content="..." Click="ChangeMyVar_Click"/>

The code of window

public partial class ConfigureWindow : Window, INotifyPropertyChanged
{
    public ConfigureWindow()
    {
        InitializeComponent();
    }

    private void ChangeMyVar_Click(object sender, RoutedEventArgs e)
    {
        Properties.Settings.Default.MyVar = "Changed";
        Properties.Settings.Default.Save();

        OnPropertyChanged("MyVar");
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string info)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(info));
    }
}

Debugging I see the handler always is null. My INotifyPropertyChanged is wrong implemented? Or I can't update the UI using the Properties.Settings? How to fix that? Thanks.

Upvotes: 1

Views: 3839

Answers (1)

brunnerh
brunnerh

Reputation: 184296

This:

Source={StaticResource settings}

Looks like you do not bind to the default settings but another instance, so if you change the default settings the binding of course will not update as its source has not been changed at all. Use:

xmlns:prop="clr-namespace:WpfApplication.Properties"
Source={x:Static prop:Settings.Default}

Changing the property should be enough, for changes to be noticed by the UI the class containing the property needs to fire change notifications, so your notification will not do anything. However in this case you do not need to do anything at all because the application settings class does implement INPC, you just need to bind to the correct instance.

Upvotes: 3

Related Questions