In our RIA Services application, we’re using the AutoCompleteBox control, but what if you want to select something from the list, press Enter and bind to a Command in a viewmodel? Sort of like the Button Command property.
I decided to extend the control and add a “Command” DependencyProperty for an ICommand which is executed when Enter is pressed and if an item is selected in the AutoCompleteBox. Works for us:
public class AutoCompleteBoxEx : AutoCompleteBox
{
protected override void OnKeyDown(KeyEventArgs e)
{
if (SelectedItem != null && e.Key == Key.Enter)
{
if (Command != null)
Command.Execute(SelectedItem);
}
base.OnKeyDown(e);
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command",
typeof(ICommand),
typeof(AutoCompleteBoxEx),
null);
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
}