2010-11-17 7 views

Odpowiedz

3

wygląda wszystko gwintowania część w mvvmlight jest ta klasa:

public static class DispatcherHelper 
{ 

    public static Dispatcher UIDispatcher 
    { 
     get; 
     private set; 
    } 

    /// <summary> 
    /// Executes an action on the UI thread. If this method is called 
    /// from the UI thread, the action is executed immendiately. If the 
    /// method is called from another thread, the action will be enqueued 
    /// on the UI thread's dispatcher and executed asynchronously. 
    /// <para>For additional operations on the UI thread, you can get a 
    /// reference to the UI thread's dispatcher thanks to the property 
    /// <see cref="UIDispatcher" /></para>. 
    /// </summary> 
    /// <param name="action">The action that will be executed on the UI 
    /// thread.</param> 
    public static void CheckBeginInvokeOnUI(Action action) 
    { 
     if (UIDispatcher.CheckAccess()) 
     { 
      action(); 
     } 
     else 
     { 
      UIDispatcher.BeginInvoke(action); 
     } 
    } 

    /// <summary> 
    /// This method should be called once on the UI thread to ensure that 
    /// the <see cref="UIDispatcher" /> property is initialized. 
    /// <para>In a Silverlight application, call this method in the 
    /// Application_Startup event handler, after the MainPage is constructed.</para> 
    /// <para>In WPF, call this method on the static App() constructor.</para> 
    /// </summary> 
    public static void Initialize() 
    { 
     if (UIDispatcher != null) 
     { 
      return; 
     } 

     // for silverlight 
     UIDispatcher = Deployment.Current.Dispatcher; 

     // wpf 
     //IDispatcher = Dispatcher.CurrentDispatcher; 

    } 
} 

}

i to wszystko. Użyj DispatcherHelper.Initialize() zgodnie z skomentować w statycznym konstruktorze aplikacji (WPF) lub obsługi zdarzeń Application_Startup (Silverlight) - a następnie u mogą korzystać DispatcherHelper.CheckBeginInvokeOnUI (Akcja Akcja)

Pozdrowienia

+0

Dzięki agend. Co powiesz na porównanie z normalnym wątkiem .net i czy można go użyć w widokach? –

+0

1. first u initialize DispatcherHelper class calling Initialize() method - i u musisz zrobić to w wątku interfejsu użytkownika, aby mógł zapamiętać/ustawić swoje prywatne odwołanie do dispatchera – agend

+0

2. po tym możesz użyć DispatcherHelper.CheckBeginInvokeOnUI (akcja akcji) - z dowolnego miejsca, w którym chcesz - widok, model, viewmodel - zawsze użyjemy wątku interfejsu użytkownika, aby wywołać twoje działanie. 3. o normalnym porównaniu z wątkiem .net - normalnie będziesz musiał zrobić to samo: zachowaj odniesienie do interfejsu użytkownika dispatcher, sprawdź, czy jesteś w tym wątku, a na końcu zadzwoń do dispatcher.BeginInvoke (action) - w tej klasie jest łatwiej – agend