The simple way to do this would be data binding. In WPF this is quite easy. You can bind the data from one control to another. Below I have bound a TextBox, which has taken the user input, to a Label which displays it.
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="45,55,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
<Label Content="{Binding ElementName=textBox1, Path=Text}" Height="28" HorizontalAlignment="Left" Margin="45,135,0,0" Name="label1" VerticalAlignment="Top" Width="142" />
</Grid>
The more complex answer would be to do Command binding. What this does is catches specific key bindings on a UserControl or Window and executes a given command. This is a little more complex because it requires you to create a class that implements ICommand.
More info here:
http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx
I personally am a big fan of the RelayCommand implementation by Josh Smith. There is a great article here.
In short though you can do this.
XAML:
<Window.InputBindings>
<KeyBinding Key="Escape" Command="{Binding KeyPressCommand}"/>
</Window.InputBindings>
CODE:
You will need to create a RelayCommand Class.
public class RelayCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute(parameter);
}
And then to implement this in your main window you will need to do this.
private RelayCommand _keyPressCommand;
public RelayCommand KeyPressCommand
{
get
{
if (_keyPressCommand== null)
{
_keyPressCommand = new RelayCommand(
KeyPressExecute,
CanKeyPress);
}
return _keyPressCommand;
}
}
private void KeyPressExecute(object p)
{
// HANDLE YOUR KEYPRESS HERE
}
private bool CanSaveZone(object parameter)
{
return true;
}
If you go with the second option I really suggest you take a look at the MSDN article by Josh Smith.