Question

I build up a custom TreeView class, with settings for each node such as "name/background" etc. I also have a ICommand property that can be set so that each node can have a custom method executed if necessary.

I build all of this in a "treeview service class", which then sends the menu to the usercontrol via MVVMLight Messenger. This all works just fine, but my problem is that if i dont specify a custom command for the node, i want it to execute a "default action", which should be located in the viewmodel that recieves the message from the Messenger service.

Basically my question is: How do i expose a RelayCommand in the MainViewModel , so that i can reference it from another viewmodel (or my service class), when building my tree.

Était-ce utile?

La solution

To reference ViewModel A in ViewModel B you can use MVVMLight´s ViewModelLocator like in the Template samples:

Your ViewModelLocator class:

 public class ViewModelLocator
 {
    static ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
        // Register your services
        //...
        // Register your ViewModels
        SimpleIoc.Default.Register<MainViewModel>();
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
        "CA1822:MarkMembersAsStatic",
        Justification = "This non-static member is needed for data binding purposes.")]
    public MainViewModel Main
    {
        get
        {
            return ServiceLocator.Current.GetInstance<MainViewModel>();
        }
    }
}

and in your NodeViewModel you could access your default command for example like this:

  public class NodeViewModel : ViewModelBase
  {
    private ViewModelLocator locator = new ViewModelLocator();

    public RelayCommand NodeCommand
    {
        get
        {
            return locator.Main.DefaultCommand;
        }
    }
}

You can find a full small sample when you create a MVVM Light project by using the MVVM Light visual studio templates.

hope this helps!

Autres conseils

I believe RelayCommand is an ICommand. You can just expose it as a property on the viewmodel:

public ICommand MyCommand { get; set;} 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top