0

我正在开发一个 C# WPF 应用程序,它使用 Windows 窗体 PropertyGrid 来允许用户查看和更改对象的属性。我希望某些属性可见但已锁定,因此我将它们的 ReadOnly 属性设置为 true。

但是,在项目的其他地方,我们使用 XAML 序列化程序来序列化对象,并发现具有 ReadOnly 属性集的属性正在从序列化中省略。

为了证明这一点:

// Simple class containing 3 properties, one of which has a ReadOnly attribute
public class TestClass
{
    public int a { get; set; }
    [ReadOnly(true)]
    public int b { get; set; }
    public int c { get; set; }
}

运行此代码:

TestClass test = new TestClass();

test.a = 1;
test.b = 2;
test.c = 3;

string xStr = XamlWriter.Save(test);

Console.WriteLine(xStr);

给出输出:

<TestClass a="1" c="3" xmlns="clr-namespace:myTest;assembly=myTest" />

显然缺少“b”属性。

这是正确的行为吗?是否可以序列化 ReadOnly 设置为 true 的属性?

4

1 回答 1

0

如果您很高兴您的输出可能无法反序列化,那么您可以通过以下方式装饰您的[ReadOnly(true)]属性来实现您想要的:

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
于 2015-04-20T19:26:41.113 回答