View Code
 1 <UserControl x:Class="Coinstar.Coin.Kiosk.Administration.Ui.ServiceMode.Views.IOBoardDeviceView"
2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
5 xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" mc:Ignorable="d"
6 d:DesignHeight="700" d:DesignWidth="1280">
7 <i:Interaction.Behaviors>
8 <bi:KeyPadPressBehavior PressAction="{Binding KeyPadAction}"/>
9 </i:Interaction.Behaviors>
10 <Grid>
11 ...
12 ...
13 ...
14 </Grid>
15 </UserControl>

 

Behavior Code
 1 public class KeyPadPressBehavior : Behavior<Control>
2 {
3 public readonly static DependencyProperty PressActionProperty = DependencyProperty.Register("PressAction", typeof(Action<Key>), typeof(KeyPadPressBehavior));
4
5 public Action<Key> PressAction
6 {
7 get { return (Action<Key>)GetValue(PressActionProperty); }
8 set { SetValue(PressActionProperty, value); }
9 }
10
11 protected override void OnAttached()
12 {
13 base.OnAttached();
14 if (AssociatedObject != null)
15 {
16 AssociatedObject.KeyDown += new KeyEventHandler(AssociatedObjectKeyDown);
17 }
18 }
19
20 protected override void OnDetaching()
21 {
22 base.OnDetaching();
23 if (AssociatedObject != null)
24 {
25 AssociatedObject.KeyDown -= new KeyEventHandler(AssociatedObjectKeyDown);
26 }
27 }
28
29 private void AssociatedObjectKeyDown(object sender, KeyEventArgs e)
30 {
31 if (PressAction != null)
32 {
33 PressAction.Invoke(e.Key);
34 }
35 }
36 }

 

Behind Code
 1 public class TestViewModel : ViewModelBase
2 {
3 private Action<Key> _keyPadAction;
4
5 public Action<Key> KeyPadAction
6 {
7 get
8 {
9 return _keyPadAction;
10 }
11 set
12 {
13 if (_keyPadAction != value)
14 {
15 _keyPadAction = value;
16 RaisePropertyChanged("KeyPadAction");
17 }
18 }
19 }
20
21 public override void OnActivated()
22 {
23 base.OnActivated();
24 KeyPadAction = new Action<Key>(PressKeyAction);
25 }
26
27 private void PressKeyAction(Key key)
28 {
29 switch(key)
30 case Key.A:
31 ...
32 ...
33 }
34 }

 

posted on 2011-12-23 16:56  Damon-Cui  阅读(184)  评论(0编辑  收藏  举报