本文介绍了是否可以复制某个控件的所有属性?(C# 窗体)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个带有蓝色 BackgroundColor 属性等的 DataGridView 控件,有没有一种方法可以将这些属性以编程方式传输或传递给另一个 DataGridView 控件?

For example, I have a DataGridView control with a Blue BackgroundColor property etc.., is there a way which I can transfer or pass programatically these properties to another DataGridView control?

像这样:

dtGrid2.Property = dtGrid1.Property; // but of course, this code is not working

谢谢...

推荐答案

你需要使用反射.

获取对源控件中每个属性的引用(基于其类型),然后获取"其值 - 将该值分配给目标控件.

You grab a reference to each property in your source control (based on its type), then "get" its value - assigning that value to your target control.

这是一个粗略的例子:

    private void copyControl(Control sourceControl, Control targetControl)
    {
        // make sure these are the same
        if (sourceControl.GetType() != targetControl.GetType())
        {
            throw new Exception("Incorrect control types");
        }

        foreach (PropertyInfo sourceProperty in sourceControl.GetType().GetProperties())
        {
            object newValue = sourceProperty.GetValue(sourceControl, null);

            MethodInfo mi = sourceProperty.GetSetMethod(true);
            if (mi != null)
            {
                sourceProperty.SetValue(targetControl, newValue, null);
            }
        }
    }

这篇关于是否可以复制某个控件的所有属性?(C# 窗体)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 00:32