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

92 lines
3.2 KiB
C#

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using DTS.Common.Controls;
using DTS.Common.Events;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.ServiceLocation;
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;
}
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 == sender && sender is ChannelCodeBuilder ccb)
{
textBox = ccb.MainEditBox;
}
else if (null == sender && sender is ChannelNameBuilder cnb)
{
textBox = cnb.MainEditBox;
}
var command = GetPasteCommand(textBox);
try
{
var text = Clipboard.GetText();
var lines = text.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
if (command.CanExecute(null))
command.Execute(textBox);
e.Handled = true;
}
catch (Exception ex)
{
var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
eventAggregator.GetEvent<PageErrorEvent>().Publish(new PageErrorArg(new[] {ex.Message}, null));
}
}
}
}