How to pass the UI Dispatcher to the ViewModel

前端 未结 16 628
独厮守ぢ
独厮守ぢ 2020-11-28 02:16

I\'m supposed to be able to access the Dispatcher that belongs to the View I need to pass it to the ViewModel. But the View should not know anything about the ViewModel, so

16条回答
  •  独厮守ぢ
    2020-11-28 02:38

    hi maybe i am too late since it has been 8 months since your first post... i had the same proble in a silverlight mvvm applicatioin. and i found my solution like this. for each model and viewmodel that i have, i have also a class called controller. like that

    public class MainView : UserControl  // (because it is a silverlight user controll)
    public class MainViewModel
    public class MainController
    

    my MainController is in charge of the commanding and the connection between the model and viewmodel. in the constructor i instanciate the view and its viewmodel and set the datacontext of the view to its viewmodel.

    mMainView = new MainView();
    mMainViewModel = new MainViewModel();
    mMainView.DataContext = mMainViewModel; 
    

    //(in my naming convention i have a prefix m for member variables)

    i also have a public property in the type of my MainView. like that

    public MainView View { get { return mMainView; } }
    

    (this mMainView is a local variable for the public property)

    and now i am done. i just need to use my dispatcher for my ui therad like this...

    mMainView.Dispatcher.BeginInvoke(
        () => MessageBox.Show(mSpWeb.CurrentUser.LoginName));
    

    (in this example i was asking my controller to get my sharepoint 2010 loginname but you can do what your need)

    we are almost done you also need to define your root visual in the app.xaml like this

    var mainController = new MainController();
    RootVisual = mainController.View;
    

    this helped me by my application. maybe it can help you too...

提交回复
热议问题