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



我的目标是让我的应用程序共享数据、首选项等拥有一个单列表。我希望它在整个应用程序中是单例的,并希望它在使用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); }
    }
}

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

public class MyViewModel : ViewModelBase 
{
    public static MyViewModel Instance { get; set; }
    public static ICommand MyCommand { get; set; }
    public MyViewModel()
    {
        Instance = this;
    }
}

和绑定按钮等,像这样:

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

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

最新更新