Pages

Saturday 5 June 2010

Linking TextBox Key Presses to a DelegateCommand

I needed to detect the <return> key being pressed in a TextBox. The original technique used a KeyPress event and a small event handler in the code-behind. Since we're using MVVM I wanted to replace the event handler with a DelegateCommand.
This .Net 4 only solution binds the DelegateCommand to the Command property of a KeyBinding.

...
KeyReturnCommand = new DelegateCommand(ReturnKeyPressed);
...
public DelegateCommand KeyReturnCommand { get; set; }
private void ReturnKeyPressed(string text)
{
MessageBox.Show(text);
}

<TextBox x:Name="SearchText" Width="100" Height="25">
<TextBox.InputBindings>
<KeyBinding
Command="{Binding KeyReturnCommand}"
CommandParameter="{Binding ElementName=SearchText, Path=Text}"
Key="Enter"/>
</TextBox.InputBindings>
</TextBox>

Wednesday 2 June 2010

Current Item Pointers

Views also support the notion of a current item. You can navigate through the objects in a collection view. As you navigate, you are moving an item pointer that allows you to retrieve the object that exists at that particular location in the collection.
 

Because WPF binds to a collection only by using a view (either a view you specify, or the collection's default view), all bindings to collections have a current item pointer. When binding to a view, the slash ("/") character in a Path value designates the current item of the view.

 

In the following example, the data context is a collection view. The first line binds to the collection. The second line binds to the current item in the collection. The third line binds to the Description property of the current item in the collection.

 
<Button Content="{Binding }" />
<Button Content="{Binding Path=/}" />
<Button Content="{Binding Path=/Description}" />

Debugging Bindings

I just want to keep track of this page to remind me how to get more information about a binding when debugging binding issues.

PresentationTraceSources.TraceLevel