更新Properties.Settings绑定

时间:2012-08-12 17:09:17

标签: c# wpf xaml data-binding settings

我在UI中有一个readonly文本框,它绑定到Properties.Settings.Default.MyVar,当窗口打开时,绑定正确获取值。但是当用户单击一个按钮(此按钮更改Properties.Setting.Default.MyVar)时,文本框不会更新(但如果我关闭窗口并再次打开它,那么我将获得新值)。我已经尝试过UpdataSourceTrigger但是没有用。

我的xml:

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

窗口代码

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

调试我看到处理程序总是为空。我的INotifyPropertyChanged实现错误了吗?或者我无法使用Properties.Settings更新UI? 如何解决?感谢。

1 个答案:

答案 0 :(得分:3)

此:

Source={StaticResource settings}

看起来您没有绑定到默认设置而是另一个实例,因此如果您更改默认设置,绑定当然不会更新,因为它的源根本没有更改。使用:

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

更改属性应该足够了,UI要注意更改包含属性的类需要触发更改通知,因此您的通知不会执行任何操作。但是在这种情况下,您根本不需要执行任何操作,因为应用程序设置类实现了INPC,您只需要绑定到正确的实例。

相关问题