【问题标题】:Categories are not shown in PropertyGrid for a collection<T>, when all the properties of <T> are read-only当 <T> 的所有属性都是只读的时,集合<T> 的类别不会显示在 PropertyGrid 中
【发布时间】:2018-12-18 10:12:08
【问题描述】:

正如标题所说,我注意到当类“T”的所有属性都是只读的时,类别没有显示在集合(T 的默认集合编辑器中)的 **PropertyGrid*(在其默认集合编辑器中) .

下面的代码代表我的代码结构:

C#:

[TypeConverter(typeof(ExpandableObjectConverter))]
public class TestClass1 {

    public TestClass2 TestProperty1 {get;} = new TestClass2();
}

[TypeConverter(typeof(ExpandableObjectConverter))]
public sealed class TestClass2 {

    [TypeConverter(typeof(CollectionConverter))]
    public ReadOnlyCollection<TestClass3> TestProperty2 {
        get {
            List<TestClass3> collection = new List<TestClass3>();
            for (int i = 0; i <= 10; i++) {
                collection.Add(new TestClass3());
            }
            return collection.AsReadOnly();
        }
    }
}

[TypeConverter(typeof(ExpandableObjectConverter))]
public sealed class TestClass3 {

    [Category("Category 1")]
    public string TestProperty3 {get;} = "Test";
}

VB.NET:

<TypeConverter(GetType(ExpandableObjectConverter))>
Public Class TestClass1

    Public ReadOnly Property TestProperty1 As TestClass2 = New TestClass2()

End Class

<TypeConverter(GetType(ExpandableObjectConverter))>
Public NotInheritable Class TestClass2

    <TypeConverter(GetType(CollectionConverter))>
    Public ReadOnly Property TestProperty2 As ReadOnlyCollection(Of TestClass3)
        Get
            Dim collection As New List(Of TestClass3)
            For i As Integer = 0 To 10
                collection.Add(New TestClass3())
            Next
            Return collection.AsReadOnly()
        End Get
    End Property

End Class

<TypeConverter(GetType(ExpandableObjectConverter))>
Public NotInheritable Class TestClass3

    <Category("Category 1")>
    Public ReadOnly Property TestProperty3 As String = "Test"

End Class

问题在于 TestProperty3。只读时,属性网格中不显示类别(“类别 1”)...

但如果我将属性设置为可编辑,则显示类别...

C:#

[Category("Category 1")]
public string TestProperty3 {get; set;} = "Test";

VB.NET:

<Category("Category 1")>
Public Property TestProperty3 As String = "Test"

不仅如此,让我们假设在 TestClass3 中声明了 10 个属性(而不是本示例中的 1 个),其中 9 个是只读的,1 个是可编辑的,那么,在这种情况下会显示所有类别。另一方面,如果所有 10 个属性都是只读的,则不会显示类别。

PeopertyGrid 的这种行为对我来说非常烦人和意外。我希望看到我的自定义类别,无论在我的类中是否声明了带有 setter 的属性。

我必须显示哪些类别具有我的类的所有属性都是只读的?也许编写自定义 TypeConverter 或集合编辑器可以解决这种烦人的视觉表现行为?

【问题讨论】:

  • 查看这个答案:How to set IsReadOnly for a property for a usercontrol。您可以使用它来更改/fake 具有 empty set 的属性的只读方面(有一个设置器,但它实际上什么也没设置)。也许这不是完美的解决方案,但它可能很有用。
  • 有了 它可能很有用 我的意思是提供的解决方案有一些特殊的实现,可用于自定义 TypeDescriptionProvider,添加一些缺失的功能。

标签: c# .net vb.net generics propertygrid


【解决方案1】:

这不是PropertyGrid 的错,而是CollectionEditor 的CollectionForm 的功能(错误?)。

如果您将TestClass3 的实例直接分配给属性网格,您将看到属性网格按预期显示类别下的属性。但是当CollectionForm 试图在其属性网格中显示TestClass3 的实例时,由于它没有任何可设置的属性并且它的集合转换器不支持创建项目实例,然后它决定将对象包装到另一个派生自定义类型描述符的对象,显示与类名同名的类别下的所有属性。

正如其他答案已经建议的那样,您可以通过

修复它
  • 向您的类添加一个虚拟的不可浏览的可写属性
  • 或者通过注册一个新的类型描述符,当它被要求返回属性列表时,它会返回一个虚拟的不可浏览的可写属性

但我不希望仅仅因为 CollectionForm 错误而更改类或其类型描述符。

由于问题出在CollectionForm 或CollectiorEditor,作为另一种选择,您可以通过创建从CollectionEditor 派生的集合编辑器并覆盖其CreateCollectorForm 方法并在尝试更改其行为时更改其行为来解决问题在集合编辑器窗体中设置属性网格的选定对象:

public class MyCollectionEditor<T> : CollectionEditor
{
    public MyCollectionEditor() : base(typeof(T)) { }
    public override object EditValue(ITypeDescriptorContext context, 
        IServiceProvider provider, object value)
    {
        return base.EditValue(context, provider, value);
    }
    protected override CollectionForm CreateCollectionForm()
    {
        var f = base.CreateCollectionForm();
        var propertyBrowser = f.Controls.Find("propertyBrowser", true)
            .OfType<PropertyGrid>().FirstOrDefault();
        var listbox = f.Controls.Find("listbox", true)
           .OfType<ListBox>().FirstOrDefault();
        if (propertyBrowser != null && listbox !=null)
            propertyBrowser.SelectedObjectsChanged += (sender, e) =>
            {
                var o = listbox.SelectedItem;
                if (o != null)
                    propertyBrowser.SelectedObject =
                        o.GetType().GetProperty("Value").GetValue(o);
            };
        return f;
    }
}

那么用这个属性来装饰TesProperty2就够了:

[Editor(typeof(MyCollectionEditor<TestClass3>), typeof(UITypeEditor))]

【讨论】:

  • 太棒了。我认为没有比这更好的解决方案了。谢谢!。
  • 你应该提到这依赖于集合编辑器的内部/未记录的对象,所以它不是没有风险/没有未来的。
  • 另外,您必须更改类(向属性添加属性)才能使其工作。
  • 另一方面,这个故障/功能本身并没有记录,如果不阅读内部实现,我们无法提供任何解决方案,包括添加一个虚拟的不可浏览的可写属性或更改添加此类属性描述符。虽然在很多情况下我也使用类型描述并且我真的很喜欢它,但我不能说注册一个新的集合编辑器不安全或者比添加虚拟属性或属性描述符风险更大。注册 Editor 属性是 Windows 窗体中非常自然且常见的场景。
  • 让我说我喜欢这两种解决方案,至少在我的场景中它们都是有效的,但最后我不能选择/接受多个答案。也许我错了,但我觉得这个解决方案通过继承 CollectionEditor 类更接近问题的根源(集合编辑器),也许由于这个原因,生成的代码按比例更小并且比为 TypeDescriptionProvider 方法编写 3 个类的需要“更干净”。这不会让 Simon Mourier 的回答变得最糟糕,只是一种不同的方法,但也很有效。谢谢你们的帮助。
【解决方案2】:

这确实是一个非常讨厌的行为。但是,我不相信您可以绕过它:它不是有问题的属性描述符 - 它正在报告正确的类别 - 您可以通过以下方式进行验证:

var props = TypeDescriptor.GetProperties(new TestClass3());
foreach(PropertyDescriptor prop in props)
{
    Console.WriteLine($"{prop.Category}: {prop.Name}");
}

输出Category 1: TestProperty3。

所以;这只是集合编辑器 UI 控件的一个怪癖。奇怪的是,如果您添加第二个 writable 属性,它会开始显示两者的类别。但是,如果您添加第二个 只读 属性:它不会显示类别。这适用于仅限get 的属性和标记为[ReadOnly(true)] 的属性。

所以:我认为这里没有一个好的解决方案,除了可能使用不同的属性网格实现,或者添加一个虚拟的可写属性 - 抱歉!


作为一个侧面/不相关的说明:当使用{get;set;} = "initial value"; 样式初始化(​​或构造函数初始化)时,最好将[DefaultValue("initial value")] 添加到该属性,以便它获得ShouldSerialize*() 行为正确(或PropertyGrid 术语:因此它是适当的粗体/非粗体),但是......这不会解决您看到的问题,抱歉。

【讨论】:

  • 非常感谢您提供详细信息的回答,但正如您所理解的,强制声明可写属性不是我认为的解决方案,因为它没有解决问题,而是解决了问题。跨度>
  • 关于你的话:“这只是集合编辑器 UI 控件的一个怪癖” - 看,有一件事是肯定的:有一个“标志”(无论如何,就像算法一样,返回值函数或布尔变量),它告诉 PropertyGrid 和/或 CollectionEditor 本身何时显示类别以及何时不显示类别。在 PropertyGrid 或 CollectionEditor 类中的某处(或者可能在继承的类之一中),它检查对象的所有属性是否都是只读的,如果所有属性都是只读的,那么指示显示类别的“标志”将停用。 ..
  • 那么,您是否认为,在深入分析公共 .NET 参考源代码中的 PropertyGrid 和 CollectionEditor 类之后,开始通过 Reflection 编写解决方案以获得我的 PropertyGrid 中的 CollectionEditor 实例来激活强制显示类别的“标志”?你认为有可能吗?。
  • 事实上,我正在分析 PropertyGridd、PropertyGridView、UITypeEditor、CollectionEditor 和其他相关类的源代码,但它是一场噩梦,有大量声明的成员,甚至搜索特定的关键字来丢弃非源代码的相关部分仍然很难(至少对我而言)尝试确定集合编辑器决定显示类别的方式和位置。但是,嘿,至少我尝试自己做。
【解决方案3】:

向您班级中的虚拟可写但不可浏览属性问好。

当然,这是属性网格错误(?)的解决方法,但考虑到创建自定义集合编辑器表单和实现自定义 UITypeEditor 所需的开销,而后者又将使用您的自定义表单来克服这种行为,它应该至少被命名为一个半优雅的解决方案。

代码:

Imports System.Collections.ObjectModel
Imports System.ComponentModel

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim tc1 As New TestClass1
        PropertyGrid1.SelectedObject = tc1
    End Sub

    <TypeConverter(GetType(ExpandableObjectConverter))>
    Public Class TestClass1
        Public ReadOnly Property TestProperty1 As TestClass2 = New TestClass2()
    End Class

    <TypeConverter(GetType(ExpandableObjectConverter))>
    Public NotInheritable Class TestClass2
        <TypeConverter(GetType(CollectionConverter))>
        Public ReadOnly Property TestProperty2 As ReadOnlyCollection(Of TestClass3)
            Get
                Dim collection As New List(Of TestClass3)
                For i As Integer = 0 To 10
                    collection.Add(New TestClass3())
                Next
                Return collection.AsReadOnly()
            End Get
        End Property
    End Class

    <TypeConverter(GetType(ExpandableObjectConverter))>
    Public NotInheritable Class TestClass3
        <Category("Category 1")>
        Public ReadOnly Property TestProperty1 As String = "Test 1"
        <Category("Category 1")>
        Public ReadOnly Property TestProperty2 As String = "Test 2"
        <Category("Category 1")>
        Public ReadOnly Property TestProperty3 As String = "Test 3"
        <Category("Category 2")>
        Public ReadOnly Property TestProperty21 As String = "Test 21"
        <Category("Category 2")>
        Public ReadOnly Property TestProperty22 As String = "Test 22"
        <Category("Category 2")>
        Public ReadOnly Property TestProperty23 As String = "Test 23"
        'We use the following dummy property to overcome the problem with the propertygrid
        'that it doesn't display the categories once all the properties in the category
        'are readonly...
        <Browsable(False)>
        Public Property DummyWriteableProperty As String
            Get
                Return String.Empty
            End Get
            Set(value As String)

            End Set
        End Property
    End Class

End Class

这些是带有和不带有虚拟属性的结果:

如果您仍想为您的集合实现自定义编辑器,请查看this thread 中接受的答案。它没有经历整个过程,但它是一个很好的起点。

希望这会有所帮助。

【讨论】:

  • 您扩展了有关@Marc Gravell 答案中模糊提到的解决方法的信息。我知道 BrowsableAttribute 类及其在这种情况下的影响,但无论如何我很感激收到答案,但是,正如我在 Marc 回答的评论框中提到的那样:“强制声明可写属性不是我认为的解决方案,因为它没有解决问题,而是解决了问题”。我在“TestClass3”中声明的成员结构不应该改变。我希望你能理解我的观点,这不是我期望的答案/解决方案。无论如何,谢谢。
  • @ElektroStudios 当然我理解你的观点,不用担心。我在此处发布了我的答案,以作为此错误的解决方法。我也有许多只有只读属性的类,我使用了这个解决方法,因为没有办法通过使用属性网格允许的东西(属性装饰等)来修复这个错误,而不是实现你自己的集合编辑器表单然后实现自定义 UITypeEditor 以使用该表单而不是默认表单。但是,由于默认集合编辑器表单使用属性网格,您可以看到实现正确解决方案所需的开销。
【解决方案4】:

这不是错误,属性网格就是这样设计的。如果组件的所有属性都是只读的,则组件被认为是“不可变的”。在这种情况下,它被包装到那个时髦的“Value”包装器属性中。

一种解决方案是在出现问题的类(或实例)上声明一个自定义TypeDescriptionProvider。 此提供程序将返回一个 custom type descriptor 实例,该实例将添加一个虚拟的不可浏览(对属性网格不可见)非只读属性,因此该类不再被视为“不可变”。

你可以这样使用它,例如:

public Form1()
{
    InitializeComponent();

    // add the custom type description provider
    var prov = new NeverImmutableProvider(typeof(TestClass3));
    TypeDescriptor.AddProvider(prov, typeof(TestClass3));

    // run the property grid
    var c2 = new TestClass2();

    propertyGrid1.SelectedObject = c2;
}

正如预期的那样,这就是它的样子:

这是代码。

public class NeverImmutableProvider : TypeDescriptionProvider
{
    public NeverImmutableProvider(Type type)
        : base(TypeDescriptor.GetProvider(type))
    {
    }

    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) => new MyTypeProvider(base.GetTypeDescriptor(objectType, instance));

    private class MyTypeProvider : CustomTypeDescriptor
    {
        public MyTypeProvider(ICustomTypeDescriptor parent)
            : base(parent)
        {
        }

        public override PropertyDescriptorCollection GetProperties() => GetProperties(null);
        public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
        {
            var props = new List<PropertyDescriptor>(base.GetProperties(attributes).Cast<PropertyDescriptor>());
            props.Add(new MyProp());
            return new PropertyDescriptorCollection(props.ToArray());
        }
    }

    private class MyProp : PropertyDescriptor
    {
        public MyProp()
            : base("dummy", new Attribute[] { new BrowsableAttribute(false) })
        {
        }

        // this is the important thing, it must not be readonly
        public override bool IsReadOnly => false;

        public override Type ComponentType => typeof(object);
        public override Type PropertyType => typeof(object);
        public override bool CanResetValue(object component) => true;
        public override object GetValue(object component) => null;
        public override void ResetValue(object component) { }
        public override void SetValue(object component, object value) { }
        public override bool ShouldSerializeValue(object component) => false;
    }
}

此解决方案的优点是不需要对原始类进行任何更改。但它可能对你的代码有其他影响,所以你真的想在你的上下文中测试它。另外,请注意,一旦网格关闭,您可以/应该删除提供程序。

【讨论】:

  • 这是漂亮且可重用的代码,谢谢。顺便说一句,关于你的话:“但它可能会对你的代码产生其他影响”——也许你能提到任何重要的负面影响来了解它吗?。
  • 您正在更改对象的“外观”这一事实可能会对代码的其他部分产生影响,因为许多程序都使用类型描述符。但是,如果你在属性网格周围限制它,(如我所说,使用 Add and Remove after),那么它不应该造成问题
猜你喜欢
  • 2023-03-12
  • 1970-01-01
  • 2012-02-08
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-24
  • 2016-08-27
相关资源
最近更新 更多