1

我在 UI 中有一个只读文本框,它绑定到 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?如何解决?谢谢。

4

1 回答 1

3

这:

Source={StaticResource settings}

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

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

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

于 2012-08-12T17:34:33.677 回答