IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Windows Presentation Foundation Discussion :

[MVVM]Accèder aux Commands d'un VM depuis un Ribbon


Sujet :

Windows Presentation Foundation

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Étudiant
    Inscrit en
    Février 2007
    Messages
    202
    Détails du profil
    Informations personnelles :
    Âge : 38

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Février 2007
    Messages : 202
    Par défaut [MVVM]Accèder aux Commands d'un VM depuis un Ribbon
    Bonjour,

    J'utilise le pattern MVVM, du moins j'essaye, et j'ai une question.

    La voici :

    Comment faire pour que mon Ribbon puisse accéder aux Commands définis dans les ViewModels de mes UserControls ?
    Une solution serait que mes UserControls retourne un tableau contenant une liste de références vers leurs Commands.
    Comme cela, je passe cette liste de référence à mon Ribbon et j'y ai accès.

    Mais est-ce la bonne façon de faire ?

    Merci pour votre conseil,
    Steven

  2. #2
    Rédacteur
    Avatar de Thomas Lebrun
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    9 161
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 9 161
    Par défaut
    Tu peux utiliser le Mediator de Marlon Grech pour ca:

    http://marlongrech.wordpress.com/200...-applications/

    Dans ton ruban, tu notifies tes VM et dans tes VM, tu "t'abonnes" à la notification de réception d'un message.

  3. #3
    Membre confirmé
    Étudiant
    Inscrit en
    Février 2007
    Messages
    202
    Détails du profil
    Informations personnelles :
    Âge : 38

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Février 2007
    Messages : 202
    Par défaut
    Bonjour,

    J'ai essayé d'implémenter le pattern et j'ai l'erreur suivante :

    Error binding to target method. avec ArgumentException was unhandled
    Qui est levée sur la ligne en gras ci-dessous :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    /// <summary>
            /// Creates a "throw away" delegate to invoke the method on the target
            /// </summary>
            /// <returns></returns>
    		internal Delegate CreateAction()
    		{
    			object target = weakRef.Target;
    			if (target != null)
    			{		
    				// Rehydrate into a real Action
    				// object, so that the method
    				// can be invoked on the target.
    				return Delegate.CreateDelegate(
    							this.delegateType,
    							weakRef.Target,
    							method);
    			}
    			else
    			{
    				return null;
    			}
    		}
    J'ai du commettre une erreur lors de son implémentation mais je ne vois pas où...

    Voici mon code :

    Class Cible (SourceBlenderViewMode)
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     [MediatorMessageSink(MediatorMessages.Command)]
            public void Test(string message)
            {
                MessageBox.Show("\nReceived by: ColleagueA");
            }
    Ma cible est bien enregistrée auprès du Mediator :
    Class Source (SourceBlenderViewModel)
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Mediator.Register(this);
    Class Source (MenuViewModel - Ribbon)
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    public class MenuViewModel : ViewModelBase
        {
            RelayCommand _exportToExcel;
     
            public MenuViewModel()
            {
                base.DisplayName = "Menu";
            }
     
            /// <summary>
            /// Send a message to all ViewModels
            /// </summary>
            /// <param name="message">The Message to send</param>
            public void SendMessage(string Message)
            {
                //send the message
                Mediator.NotifyColleagues<string>(MediatorMessages.Command, Message);
            }
     
            #region Presentation Properties
     
            public ICommand ExportToExcelCommand
            {
                get
                {
                    if (_exportToExcel == null)
                        _exportToExcel = new RelayCommand(param => this.SendMessage("Hello"));
                    return _exportToExcel;
                }
            }
     
            #endregion //Presentation Properties
        }
    Ma classe Source et Cible hérite bien de mon ViewModelBase qui instancie Mediator avec sa propriété qui va avec.

    Voici mon stacktrace :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    "   at System.Delegate.CreateDelegate(Type type, Object firstArgument, MethodInfo method, Boolean throwOnBindFailure)\r\n
       at System.Delegate.CreateDelegate(Type type, Object firstArgument, MethodInfo method)\r\n   at MediatorLib.WeakAction.CreateAction() in C:\\SVN\\ALTO\\Mediator\\WeakAction.cs:line 49\r\n   at MediatorLib.MessageToActionsMap.GetActions(String message) in C:\\SVN\\ALTO\\Mediator\\MessageToActionsMap.cs:line 64\r\n
       at MediatorLib.Mediator.NotifyColleagues[T](String message, T parameter) in C:\\SVN\\ALTO\\Mediator\\Mediator.cs:line 69\r\n
       at ALTOApplication.ViewModel.MenuViewModel.SendMessage(String Message) in C:\\SVN\\ALTO\\ALTOApplication\\ViewModel\\Menu\\MenuViewModel.cs:line 23\r\n
       at ALTOApplication.ViewModel.MenuViewModel.<get_ExportToExcelCommand>b__0(Object param) in C:\\SVN\\ALTO\\ALTOApplication\\ViewModel\\Menu\\MenuViewModel.cs:line 33\r\n 
      at ALTOApplication.RelayCommand.Execute(Object parameter) in C:\\SVN\\ALTO\\ALTOApplication\\Command\\RelayCommand.cs:line 59\r\n
       at MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource, Boolean userInitiated)\r\n
       at System.Windows.Controls.Primitives.ButtonBase.OnClick()\r\n   at System.Windows.Controls.Button.OnClick()\r\n 
      at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)\r\n 
      at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)\r\n
       at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)\r\n
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)\r\n
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)\r\n
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)\r\n 
      at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)\r\n 
      at System.Windows.UIElement.CrackMouseButtonEventAndReRaiseEvent(DependencyObject sender, MouseButtonEventArgs e)\r\n   at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)\r\n 
      at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)\r\n
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)\r\n   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)\r\n
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)\r\n 
      at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)\r\n
       at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)\r\n   at System.Windows.Input.InputManager.ProcessStagingArea()\r\n
       at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)\r\n   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)\r\n
       at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)\r\n   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)\r\n
       at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)\r\n   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)\r\n
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)\r\n 
      at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)\r\n
       at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)\r\n
       at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)\r\n
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)\r\n
       at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)\r\n
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)\r\n
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)\r\n
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)\r\n   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)\r\n
       at System.Windows.Threading.Dispatcher.Run()\r\n
       at System.Windows.Application.RunDispatcher(Object ignore)\r\n
       at System.Windows.Application.RunInternal(Window window)\r\n
       at System.Windows.Application.Run(Window window)\r\n
       at System.Windows.Application.Run()\r\n   at ALTOApplication.App.Main() in C:\\SVN\\ALTO\\ALTOApplication\\obj\\Debug\\Application.g.cs:line 48\r\n
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)\r\n   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)\r\n
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()\r\n  
     at System.Threading.ThreadHelper.ThreadStart_Context(Object state)\r\n
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)\r\n 
      at System.Threading.ThreadHelper.ThreadStart()"
    Merci de votre aide

  4. #4
    Rédacteur
    Avatar de Thomas Lebrun
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    9 161
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 9 161
    Par défaut
    Heu... je vois pas l'appel à la méthode NotifyColleagues dans ton code....

  5. #5
    Membre confirmé
    Étudiant
    Inscrit en
    Février 2007
    Messages
    202
    Détails du profil
    Informations personnelles :
    Âge : 38

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Février 2007
    Messages : 202
    Par défaut
    Me suis trompé dans le Copier/Coller, c'est pour cela

    Je poste le code approprié demain dans la matinée quand j'y aurais accès

    Bonne soirée,
    Steven

  6. #6
    Membre confirmé
    Étudiant
    Inscrit en
    Février 2007
    Messages
    202
    Détails du profil
    Informations personnelles :
    Âge : 38

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Février 2007
    Messages : 202
    Par défaut
    Voilà, j'ai édité le post pour qu'il soit correcte

    Le NotifyColleagues est bien là à présent :p

    Merci de ton aide,
    Steven

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 1
    Dernier message: 25/09/2008, 20h33
  2. Accéder aux variables de la vue depuis Zend_Layout
    Par vg33 dans le forum Zend Framework
    Réponses: 2
    Dernier message: 29/06/2008, 23h52
  3. Réponses: 5
    Dernier message: 23/04/2007, 16h31
  4. Accéder aux objets de la form1 depuis une class
    Par Jimmy_S dans le forum Windows Forms
    Réponses: 6
    Dernier message: 23/03/2007, 22h47
  5. Réponses: 1
    Dernier message: 07/07/2006, 14h56

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo