Files
DP44/Common/DTS.Common/Behaviors/TextBoxPasteBehavior.cs
2026-04-17 14:55:32 -04:00

92 lines
3.1 KiB
C#

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using DTS.Common.Controls;
using DTS.Common.Events;
using Prism.Ioc;
using Prism.Events;
namespace DTS.Common.Behaviors
{
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);
}
private static void PasteCommandChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
TextBox textBox = sender as TextBox;
if (null == textBox && sender is ChannelCodeBuilder ccb)
{
textBox = ccb.MainEditBox;
}
else if (null == textBox && sender is ChannelNameBuilder cnb)
{
textBox = cnb.MainEditBox;
}
if (null == textBox) { return; }
var newValue = (ICommand)e.NewValue;
textBox.RemoveHandler(CommandManager.ExecutedEvent, new RoutedEventHandler(CommandExecuted));
if (newValue != null)
{
textBox.AddHandler(CommandManager.ExecutedEvent, new RoutedEventHandler(CommandExecuted), true);
}
}
private static void CommandExecuted(object sender, RoutedEventArgs e)
{
if (!(e is ExecutedRoutedEventArgs eArgs)) { return; }
if (eArgs.Command != ApplicationCommands.Paste)
{
if (eArgs.Command is RoutedUICommand secureUICommand)
{
if (secureUICommand.Name != "Paste") { return; }
}
else { return; }
}
TextBox textBox = sender as TextBox;
if (null == textBox && sender is ChannelCodeBuilder ccb)
{
textBox = ccb.MainEditBox;
}
else if (null == textBox && sender is ChannelNameBuilder cnb)
{
textBox = cnb.MainEditBox;
}
var command = GetPasteCommand(textBox);
try
{
var text = Clipboard.GetText();
if (command.CanExecute(null))
command.Execute(textBox);
e.Handled = true;
}
catch (Exception ex)
{
var eventAggregator = ContainerLocator.Container.Resolve<IEventAggregator>();
eventAggregator.GetEvent<PageErrorEvent>().Publish(new PageErrorArg(new[] { ex.Message }, null));
}
}
}
}