Alan
Alan

Reputation: 7951

In XAML is it possible to use an ElementName binding before the element it refers to is declared?

I have a UserControl with some InputBindings. I wanted to make one of the input bindings (arrow key press) execute a command on a GUI control in my UserControl . So

e.g.

<UserControl.InputBindings>
    <KeyBinding Key="Up" Command="{Binding ElementName=MyViewElement, Path=MoveUpCommand}"/>
    <KeyBinding Key="Down" Command="{Binding ElementName=MyViewElement, Path=MoveDownCommand}"/>
</UserControl.InputBindings>

But, this fails because MyViewElement is not found because I assume it is declared later in the XAML. If I move my InputBindings to the end of the XAML file everything works as intended.

I kinda prefer my InputBindings to be at the top, is it possible to make it ignore the declaration order?

Upvotes: 3

Views: 2570

Answers (3)

RonnyR
RonnyR

Reputation: 230

But, this fails because MyViewElement is not found because I assume it is declared later in the XAML.

To avoid that, you can use the following in the code behind instead of the constructor:

protected override void OnInitialized(EventArgs e)
{
    SomeCommand = new DelegateCommand(SomeExecuteMethod);

    InitializeComponent();
    base.OnInitialized(e);
}

This ensures the commands are already instantiated before you use them with:

Command="{Binding ElementName=MyUserCOntrol, Path=SomeCommand}"

Upvotes: 0

snowy hedgehog
snowy hedgehog

Reputation: 672

@Stewbob What are you talking about?

Take a look at this: http://msdn.microsoft.com/en-us/library/ms752308.aspx

<Window.CommandBindings>
  <CommandBinding Command="ApplicationCommands.Open"
                  Executed="OpenCmdExecuted"
                  CanExecute="OpenCmdCanExecute"/>
</Window.CommandBindings>

According to what you said this should never work properly but it does:

<StackPanel>
  <Menu>
    <MenuItem Command="ApplicationCommands.Paste"
              CommandTarget="{Binding ElementName=mainTextBox}" />
  </Menu>
  <TextBox Name="mainTextBox"/>
</StackPanel>

From what you said the binding comes first also it will be executed first and therefore the binding to mainTextBox should never work. Thats very not true.

Upvotes: 1

snowy hedgehog
snowy hedgehog

Reputation: 672

Sure you can do everything in XAML, including such Binding at Window level. Show more code of your XAML/MyViewElement. Maybe we could tell you how to do it without errors. Also post your error here please.

Upvotes: 0

Related Questions