在 MVVM 中返回单例值以进行绑定 [英] Return singleton value in MVVM for binding

查看:52
本文介绍了在 MVVM 中返回单例值以进行绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚是否可以使用来自单例的值作为我的绑定.我想做这样的事情?

I am trying to figure out if it is possible to use a value from a singleton as my binding. I want to do something like this?

public class MySingleton : INotifyPropertyChanged    
{
   //...inotifypropertychanged and singleton implementation

   private bool _isChecked;
   public bool IsChecked
   {
       get 
       { 
           return _isChecked; 
       }
       set
       {
          _isChecked= value;
          OnPropertyChanged("IsChecked");
       }
    }

    //...other implementation
}

public class MyViewModel : INotifyPropertyChanged
{
  //...inotifypropertychanged and other implementation

  public bool IsAllChecked { get { return MySingleton.GetInstance().IsChecked; } }
}

一些 Xaml:

<ToggleButton IsChecked = "{Binding IsAllChecked}"/>

我已经试过了,绑定似乎没有更新.我已经用 ObservableCollection 尝试过这个,它工作得很好,但其他类型不是.我认为 ObservableCollection 很特别.

I have tried this and the bindings don't seem to update. I have tried this with ObservableCollection and it works great but other types aren't. I figure that it is something special with ObservableCollection.

推荐答案

MyViewModel 不引发 PropertyChangedIsAllChecked 属性,更新UI 不会发生(ObservableCollection 是完全不同的情况 - INotifyCollectionChanged).

MyViewModel doesn't raise PropertyChanged for IsAllChecked property, update in UI will not happen (ObservableCollection is totally different case - INotifyCollectionChanged).

为什么不声明Instance 属性而不是GetInstance() 方法并直接绑定到MySingleton.Instance?

why not declare Instance property instead of GetInstance() method and bind to MySingleton.Instance directly?

"{Binding Path=IsChecked, Source={x:Static myNameSpace:MySingleton.Instance}}"

这篇关于在 MVVM 中返回单例值以进行绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆