MVVM模式下 所有控制元件共享同一事件 以TextBox只能輸入數字鍵和回車鍵為例子
阿新 • • 發佈:2019-02-02
一:首先對MvvmLight裡的ViewModel進行封裝 封裝完畢後讓ViewModel繼承DialogViewModel
public class DialogViewModel : ViewModelBase { public void PreviewKeyDownEvent(object sender,KeyEventArgs e) { TextBox text = sender as TextBox; if (e.Key > Key.D9 || e.Key > Key.NumPad9 && e.Key != Key.Enter || e.Key == Key.Space) { e.Handled = true; } } }
二:在xmal裡面進行Binding
要注意的是 要使用CallMethodAction 必須引入Microsoft的DLL Microsoft.Expression.Interactions<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:vm="clr-namespace:YunSuo.MonitorSystem.ViewModel" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" xmlns:Custom="http://www.galasoft.ch/mvvmlight" xmlns:local="clr-namespace:YunSuo.MonitorSystem" x:Class="YunSuo.MonitorSystem.MonitorSystemUI"> <UserControl.Resources> <DataTemplate x:Key="alarmText"> <TextBox Name="txtAlarm" KeyDown="txtAlarm_KeyDown" Style="{DynamicResource textStyle}" Margin="10 0 0 0" Text="{Binding DiskAlarm.threshold}"> <i:Interaction.Triggers> <i:EventTrigger EventName="PreviewKeyDown" SourceName="txtAlarm"> <ei:CallMethodAction MethodName="PreviewKeyDownEvent" TargetObject="{Binding ElementName=MonitorSystem, Path=DataContext}"/> </i:EventTrigger> <i:EventTrigger EventName="MouseEnter"> <Custom:EventToCommand Command="{Binding Mode=OneWay, Path=DataContext.MouseEnterCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}" CommandParameter="{Binding Path=DataContext, ElementName=txtAlarm}"/> </i:EventTrigger> </i:Interaction.Triggers> </TextBox> </DataTemplate> </UserControl.Resources> </UserControl>