2

我有一个画布,您可以在上面添加用户控件(由图像和文本框组成)

我试图在这些用户控件上实现剪切、复制、粘贴功能,因此上下文菜单附加到处理图像的用户控件上。用户右键单击此处并从上下文菜单中选择副本,例如我将如何着手实施,以便他们可以将其粘贴到画布上。

谁能指出我正确的方向...

4

3 回答 3

6

This can be done with RoutedCommands. A full overview is at MSDN: Commanding Overview

The short version is this: when a command source (i.e. a menu item) wants to execute a command, an event is raised. That event is handled by the nearest command binding. Cut/copy/paste commands are already included with WPF, and certain elements (namely, text boxes) already include command bindings for them.

You can define a menu item like this:

<MenuItem Header="Copy" Command="ApplicationCommands.Copy" />

And add a command binding to the UserControl like this:

<UserControl.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Copy"
                    Executed="Copy_Executed" />
</UserControl.CommandBindings>

And define the Copy_Executed method with the ExecutedRoutedEventHandler signature in the UserControl's code-behind.

Then of course do the same thing for ApplicationCommands.Paste within the canvas.

It's up to you whether you want to handle the data within your own application, or use the clipboard. If you're working with images, WPF has a Clipboard class which can work with BitmapSource objects (if you have an Image element, chances are its Source is already a BitmapSource).

于 2013-07-23T16:47:16.630 回答
0

首先,一个设计良好的 MVVM 应用程序可以使用户控件的复制/粘贴变得更加简单,因为它会将 CLR 对象序列化/反序列化到剪贴板。WPF 将在反序列化后自行处理用户控件的创建。

如果您的应用程序没有实现 MVVM。您可以使用 XamlWriter/XamlReader 将用户控件保存到 XAML 并自行重新创建它们。一个例子:

        StringBuilder outstr = new StringBuilder();

        //this code need for right XML fomating 
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.OmitXmlDeclaration = true;
        XamlDesignerSerializationManager dsm =
          new XamlDesignerSerializationManager(XmlWriter.Create(outstr, settings));
        //this string need for turning on expression saving mode 
        dsm.XamlWriterMode = XamlWriterMode.Expression;
        XamlWriter.Save(control, dsm);

        //Read control from XAML
        var frameObject = XamlReader.Parse(outstr.ToString()) as UserControl;
        if (frameObject != null)
            stackPanel.Children.Add(frameObject);

关于如何将 XAML 字符串或序列化流放入剪贴板的部分,可以参考 MSDN。

希望它可以提供帮助。

于 2013-07-23T21:22:50.200 回答
0

如果您想从代码中绑定命令(如@nmclean 解释的那样),您可以使用:

CommandBindings.Add(new CommandBinding(
    ApplicationCommands.Copy,
    (sender, args) => { /* logic here */ }));
于 2017-02-10T09:46:34.097 回答