Tuesday, January 27, 2009

How to add a binding to the CommandParameter of a KeyBinding or MouseBinding

You can't add a binding to the command parameter of an InputBinding. Although InputBinding does derive from DependencyObject, the CommandParameter property is a CLR property. It was implemented in this way as InputBindings don't sit in an inheritance context and so normal bindings are not supported.

Fortunately, this can be worked around in the same way as in my previous post:
<Window.Resources>
    <my:DataResource x:Key="cp" BindingTarget="{Binding MyCommandParameter}"/>
</Window.Resources>
<TextBox>
    <TextBox.InputBindings>
        <MouseBinding 
            Command="ApplicationCommands.Open" 
            MouseAction="LeftDoubleClick">
            <MouseBinding.CommandParameter>
                <my:DataResourceBinding DataResource="{StaticResource cp}"/>
            </MouseBinding.CommandParameter>
        </MouseBinding>
    </TextBox.InputBindings>
</TextBox>



DataResource.cs
Download sample app with source code



4 comments:

Anonymous said...

What previous post? When you comment like this, it is customary to give a link to the post you are refering to.

Dimondwoof said...

Als, what does "my:DataResource" have to do with anything? I got this far:





and then added the KeyBinding to my textbox:












but this obviously isn't the only thing that needs to be done, since the my:DataResources is failing. Why does your example bind anything that you don't give code for? How do you bind something on the page you are working with?

Dimondwoof said...

Try this again:

<Window.Resources
my:DataResource x:Key="kd" BindingTarget="{Binding Text,ElementName=testTextBox}"/>
</Window.Resources>

<TextBox x:Name="testTextBox">
<TextBox.InputBindings>
<KeyBinding Key="Enter"
Command="{StaticResource cc}">
<KeyBinding.CommandParameter>
<my:DataResourceBinding DataResource="{StaticResource kd}"/>
</KeyBinding.CommandParameter>
</KeyBinding>
</TextBox.InputBindings>
</TextBox>

Anonymous said...

The sample app works fine for me!