SynchronizationContext.Current is null on resolving with Unity in WPF

后端 未结 3 544
耶瑟儿~
耶瑟儿~ 2021-01-06 00:50

I have a WPF Code which looks something like this.

public class AlphaProductesVM : BaseModel
{
    private  ObservableCollection

        
3条回答
  •  不思量自难忘°
    2021-01-06 01:19

    I'm not sure if this will be a popular suggestion, but you could lazily create and subscribe to your collection. Then the first access to NwCustomers from the UI thread will kick everything off correctly.

    public AlphaProductesVM (){}
    
    public ObservableCollection NwCustomers
    {
        get { 
              if(_NwCustomers == null)
              {
                  _NwCustomers = new ObservableCollection();
                  var repository = new NorthwindRepository();
                      repository
                      .GetAllProducts()
                      .ObserveOn(SynchronizationContext.Current)
                      .Subscribe(AddElement);
              }
              return _NwCustomers; 
        }
    }
    

    or, if you inject the UI thread's dispatcher into your view model you can subscribe on that in the constructor.

                  var repository = new NorthwindRepository();
                      repository
                      .GetAllProducts()
                      .ObserveOn(theUIdispatcher)
                      .Subscribe(AddElement);
    

提交回复
热议问题