Wpf MVVM如何在ViewModel中处理TextBox“粘贴事件”

我使用MVVM模式开发应用程序。 我使用MVVMLight库来做到这一点。 因此,如果我需要处理TextBox TextChange事件,我在XAML中编写:

    

其中PropertyGridTextChangeViewModel Command 。 但TextBox没有Paste事件!

解决方案仅在应用程序不使用MVVM模式时才有效,因为您需要在TextBox上有链接。

     

重要细节 – 放置在DataTemplate TextBox 。 我不知道如何处理“粘贴事件”。 我希望在将文本粘贴到TextBox时调用PasteCommand 。 我需要将TextBox.TextTextBox本身作为参数传递给PasteCommandMethod

 private RelayCommand _pasteCommand; public RelayCommand PasteCommand { get { return _pasteCommand ?? (_pasteCommand = new RelayCommand(PasteCommandMethod)); } } private void PasteCommandMethod(Object obj) { } 

我可以建议回答我的问题。

类帮手。

 public class TextBoxPasteBehavior { public static readonly DependencyProperty PasteCommandProperty = DependencyProperty.RegisterAttached( "PasteCommand", typeof(ICommand), typeof(TextBoxPasteBehavior), new FrameworkPropertyMetadata(PasteCommandChanged) ); public static ICommand GetPasteCommand(DependencyObject target) { return (ICommand)target.GetValue(PasteCommandProperty); } public static void SetPasteCommand(DependencyObject target, ICommand value) { target.SetValue(PasteCommandProperty, value); } static void PasteCommandChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var textBox = (TextBox)sender; var newValue = (ICommand)e.NewValue; if (newValue != null) textBox.AddHandler(CommandManager.ExecutedEvent, new RoutedEventHandler(CommandExecuted), true); else textBox.RemoveHandler(CommandManager.ExecutedEvent, new RoutedEventHandler(CommandExecuted)); } static void CommandExecuted(object sender, RoutedEventArgs e) { if (((ExecutedRoutedEventArgs)e).Command != ApplicationCommands.Paste) return; var textBox = (TextBox)sender; var command = GetPasteCommand(textBox); if (command.CanExecute(null)) command.Execute(textBox); } } 

在XAML中使用。TextBox作为属性。

 TextBoxPasteBehavior.PasteCommand="{Binding PropertyGridTextPasted}" 

PropertyGridTextPastedViewModel命令。

最近几天我一直在努力解决这类问题。 我的第一种方法是在VM中绑定一个属性文本框(我相信你已经拥有)。 然后将ICommand绑定到事件以处理on paste事件:

  xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"      

您需要在XAML代码的适当部分中定义命名空间,然后将交互触发器作为文本框定义的一部分。 在这里,我捕获RowEditEnding事件,做一些类似于你正在尝试的东西。

命令绑定是另一个部分,如果您需要有关如何设置的更多信息,请告诉我。