还有其他方法可以做到这一点,并且可能有充分的理由不这样做,但这里有一个将命令放在用户控件上的实现:
用户控件代码(可以很容易地成为一个无外观的控件):
public partial class TestControl : UserControl
{
//Declare routed commands
public static RoutedCommand IncrementCommand;
public static RoutedCommand DecrementCommand;
static TestControl()
{
//Create routed commands and add key gestures.
IncrementCommand = new RoutedCommand();
DecrementCommand = new RoutedCommand();
IncrementCommand.InputGestures.Add(new KeyGesture(Key.Add, ModifierKeys.Control));
DecrementCommand.InputGestures.Add(new KeyGesture(Key.Subtract, ModifierKeys.Control));
}
public TestControl()
{
//Subscribe to Increment/Decrement events.
TestControl.Decremented += down;
TestControl.Incremented += up;
InitializeComponent();
}
//Declare *static* Increment/Decrement events.
public static event EventHandler Incremented;
public static event EventHandler Decremented;
//Raises Increment event
public static void IncrementMin(object o, ExecutedRoutedEventArgs args)
{
if (Incremented != null)
{
Incremented(o, args);
}
}
//Raises Decrement event
public static void DecrementMin(object o, ExecutedRoutedEventArgs args)
{
if (Decremented != null)
{
Decremented(o, args);
}
}
//Handler for static increment
private void down(object o, EventArgs args)
{
Min--;
}
//Handler for static decrement
private void up(object o, EventArgs args)
{
Min++;
}
//Backing property
public int Min
{
get { return (int)GetValue(MinProperty); }
set { SetValue(MinProperty, value); }
}
public static readonly DependencyProperty MinProperty =
DependencyProperty.Register("Min", typeof(int),
typeof(TestControl), new UIPropertyMetadata(0));
}
需要此行为的窗口需要为这些命令添加 CommandBinding。后面的窗口代码:
public MainWindow()
{
InitializeComponent();
//Raise control's static events in response to routed commands
this.CommandBindings.Add(
new CommandBinding(TestControl.IncrementCommand, new ExecutedRoutedEventHandler(TestControl.IncrementMin)));
this.CommandBindings.Add(
new CommandBinding(TestControl.DecrementCommand, new ExecutedRoutedEventHandler(TestControl.DecrementMin)));
}
这有帮助吗?
(哦,顺便说一句 - 正如所写的那样,这段代码只响应我键盘上的 +/- 键,而不是 (P)([)(]) 键上方的那些 - 我以前没有使用过按键手势。当然它可以不必纠正。)