tags:

views:

50

answers:

2

Hi, I have a WPF application which has a main window composed from several custom UserControls placed in AvalonDock containers.

I want some of the UserControls' functionality to be accessible from a toolbar and menubar in the main window. I have a command defined as this in the control like this:

    public ICommand UnfoldAllCommand
    {
        get
        {
            if (this.unfoldAllCommand == null)
            {
                this.unfoldAllCommand = new RelayCommand(param => this.UnfoldAll());
            }

            return unfoldAllCommand; 
        }
    }

Now I have this UserControl defined in main window XAML under name "editor"

    <local:Editor x:Name="editor" />

This control is also made public via Edtor property of the main window (the window is its own DataContext).

    public Editor Editor { get { return this.editor; } }

The menubar is located in the main window XAML. This definition definition of one MenuItem which triggers the UserControl's UnfoldAll command works perfectly.

    <MenuItem Header="Unfold All" Command="{Binding UnfoldAllCommand, ElementName=editor}" InputGestureText="Ctrl+U" />

However, this definition is arguably prettier, but it doesn't work (the MenuItem is clickable, but won't fire the UnfoldAll method):

    <MenuItem Header="Unfold All" Command="{Binding Editor.UnfoldAllCommand}" InputGestureText="Ctrl+U" />

Why?

A: 

Your binding looks at the DataContext, and your last binding says: Whatevers is on the DataContext, get me the property Editor, and then the property UnfoldAllCommand.

Your first binding is therefore correct.

You could set the Editor on the DataContext in code behind, en change the Binding to just UnfoldAllCommand.

After the InitializeComponents() place:

DataContext = this;
Arcturus
The window (which is its own DataContext) has the property Editor, which should be equivalent to ElementName=editor. And MSDN says subproperties can be accessed through the dot notation. I still dont understand why Editor.UnfoldAllCommand won't work...
CommanderZ
Thats correct, but has the Window set the DataContext to itself or to another object? Because when only defining a path, its looks at the path of the DataContext of your Window.
Arcturus
These are several of the window's properties: x:Name="Window" Title="MainWindow" Width="640" Height="480" DataContext="{Binding ElementName=Window}"
CommanderZ
I dont think you can set the Window to the DataContext that way. Please try: {Binding RelativeSource={RelativeSource Self}}
Arcturus
A: 

The problem was that for {Binding Editor.Property} to work, Editor must be a Dependency Property as well (not only Property).

CommanderZ