首页 > 解决方案 > 在 WPF C# 应用程序中执行标准形状实例的深层复制

问题描述

我有两个 Rectangle 实例,我想将一个的属性复制到另一个,但下面的代码会导致对副本的更改影响原始文件。

我相信我需要执行原始矩形的深层复制以避免这种行为,但我该怎么做呢?

C# WPF 应用程序。

using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            SpecialButton tmp = new SpecialButton();
            tmp.Update();
        }

        public class SpecialButton
        {
            public Rectangle Original_Properties { get; set; }
            public Rectangle Copy_Properties { get; set; }

            public void Update()
            {
                Original_Properties = new Rectangle();
                Copy_Properties = new Rectangle();

                Original_Properties.StrokeThickness = 1;
                Original_Properties.Stroke = Brushes.White;
                Original_Properties.Width = 20;
                Original_Properties.Height = 20;
                Original_Properties.Tag = "exampleTag";

                Copy_Properties = Original_Properties; // this needs to be a deep copy i think.

                Copy_Properties.Width = Copy_Properties.Width / 2;
                Copy_Properties.Height = Copy_Properties.Height / 2;
                Copy_Properties.StrokeThickness = 2;
                Copy_Properties.Tag = Original_Properties.Tag + "_selected" ;
            }
        }
    }
}

标签: c#wpf

解决方案


如果您不需要保留任何依赖属性的值源,那么深度复制 wpf UI 非常简单。XamlWriter.Save(objcet)并将XamlReader.Parse(string)为您做到这一点。

var btn1 = new Button() { Content = "click me" };
var btn2 = (Button)XamlReader.Parse(XamlWriter.Save(btn1));

推荐阅读