小编典典

是否可以复制某个控件的所有属性?(C#窗口形式)

c#

例如,我有一个DataGridView具有Blue
BackgroundColor属性等的控件,是否可以将这些属性以编程方式传递或传递给另一个DataGridView控件?

像这样:

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

谢谢…


阅读 1077

收藏
2020-05-19

共1个答案

小编典典

您将需要使用反射。

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

这是一个粗略的例子:

    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);
            }
        }
    }
2020-05-19