使用INotify for WPF绑定为设置创建静态单例/存储

时间:2016-10-04 20:13:44

标签: c# wpf data-binding singleton inotifypropertychanged

我的目标是使用我的应用程序共享数据,首选项等单独使用。希望它在我的整个应用程序中单独使用并希望它使用INotify在WPF中进行双向绑定。

我读到.net 4.5可以使用StaticPropertyChanged所以我想知道下面我是如何实现它的,因为文档似乎不太明显。

public static class Global
{
    public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
    private static void CallPropChanged(string Prop)
    {
        StaticPropertyChanged?.Invoke(Settings, new PropertyChangedEventArgs(Prop));
    }
    private static Store Settings = new Store();

    public static int setting1
    {
        get { return Settings._setting1; }
        set { if (value != Settings._setting1) { Settings._setting1 = value; CallPropChanged("setting1"); } }
    }
}

internal sealed class Store
{
    internal int _setting1;
}

我是否正确地想要完成我的目标?

编辑:做了一些修改:

public sealed class Global:INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    static readonly Global _instance = new Global();

    private int _setting1;
    private int _setting2;

    private void CallPropChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        CallPropChanged(propertyName);
        return true;
    }

    private Global() { }

    public static int setting1
    {
        get { return _instance._setting1; }
        set { _instance.SetField(ref _instance._setting1, value); }
    }
    public static int setting2
    {
        get { return _instance._setting2; }
        set { _instance.SetField(ref _instance._setting2, value); }
    }

}

1 个答案:

答案 0 :(得分:0)

我不熟悉StaticPropertyChanged,但是我已经实现了像这样的单例视图模型:

public class MyViewModel : ViewModelBase 
{
    public static MyViewModel Instance { get; set; }
    public static ICommand MyCommand { get; set; }

    public MyViewModel()
    {
        Instance = this;
    }
}
XAML中的

和绑定按钮等,如下所示:

<Button Content="Click Me" Command="{x:Static vm:MyViewModel.MyCommand}" CommandParameter="MyParameters" />

您可以使用x:Static前缀绑定到静态字段,并且您可以正常使用INotifyPropertyChanged ...您可能会注意到此特定绑定实际上并不需要VM的单例实例,而是坚持使用单例模型,你也可以绑定到{x:Static vm:MyViewModel.Instance.Whatever}