gpt4 book ai didi

c# - Wpf MVVM 如何处理 ViewModel 中的 TextBox "paste event"

转载 作者:行者123 更新时间:2023-11-30 20:23:43 28 4
gpt4 key购买 nike

我使用 MVVM 模式开发应用程序。我使用 MVVMLight 库来执行此操作。因此,如果我需要处理 TextBox TextChange 事件,我将在 XAML 中编写:

<I:EventTrigger EventName="TextChanged">
<I:InvokeCommandAction Command="{Binding PropertyGridTextChange}"/>
</I:EventTrigger>

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

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

<DataTemplate x:Key="StringTemplate">
<TextBox Text="{Binding Value, ValidatesOnDataErrors=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
</TextBox>
</DataTemplate>

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

private RelayCommand<Object> _pasteCommand;
public RelayCommand<Object> PasteCommand
{
get
{
return _pasteCommand ?? (_pasteCommand =
new RelayCommand<Object>(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}"

PropertyGridTextPasted - ViewModel 中的命令。

关于c# - Wpf MVVM 如何处理 ViewModel 中的 TextBox "paste event",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28346652/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com