Search code examples
c#wpfxamlmvvmavalondock

How to use ApplicationCommands in a MVVM AvalonDock Program?


I'm working on a program that use AvalonDock to open several documents at the same time. And there is a public ribbon which has some common buttons on the top, like this: enter image description here

Now, Cut, Copy, Paste, Delete can be used by clicking MenuItems of them in ContextMenu.

However, there are some problems when I want to bind these commands to buttons in the ribbon.

Imitating the example of AvalonDock, my XAML is

 <DockingManager DocumentsSource="{Binding Documents}" ActiveContent="{Binding ActiveDocument,Mode=TwoWay}">
    <DockingManager.LayoutItemTemplateSelector>
        <local:PanesTemplateSelector>
            <local:PanesTemplateSelector.ShapesDocumentTemplate>
                <DataTemplate>
                    <view:ShapesDocument/>
                </DataTemplate>
            </local:PanesTemplateSelector.ShapesDocumentTemplate>
        </local:PanesTemplateSelector>
    </DockingManager.LayoutItemTemplateSelector>
 </DockingManager>

And my C# is:

public ObservableCollection<ShapesDocumentViewModel> Documents { get; set; } = new ObservableCollection<ShapesDocumentViewModel>();

So the ActiveDocument is a ViewModel.

In my ShapesDocument, there is a CanvasEx with Cut_Executed,Copy_Executed...

So, how can I bind the CommandTarget? Or there will be some ways to move the Executeds into ViewModel?

<Button Command="{x:Static ApplicationCommands.Cut}" CommandTarget="{Binding ???}"/>

Solution

  • Temporarily, I use MenuItems to replace the buttons. I set the ApplicationCommands in the Control in ShapeDocument UserControl, and binding them to MenuItems without setting the command targets.

    I guess that WPF can automaticly search the target of menuitems, but not button. So I can change them to MenuItems, and change the MenuItems' style to imitate buttons.

    It's not very elegant but very convinent, with very simple codes.