您当前的位置: 首页 >  c#

君子居易

暂无认证

  • 0浏览

    0关注

    210博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

c# - WPF MVVM如何在ViewModel中处理TextBox“粘贴事件”

君子居易 发布时间:2020-06-05 10:10:43 ,浏览量:0

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中的命令。

关注
打赏
1660814979
查看更多评论
立即登录/注册

微信扫码登录

0.0359s