Winforms属性网格 - 属性不可编辑

5

你好,这是我在stackoverflow上的第一个问题,请谅解如果我做了什么愚蠢的事情。我的问题是我正在开发一个关卡编辑器,并且想使用PropertyGrid控件来编辑瓷砖/实体等的属性。到目前为止一切都正常,值正确显示,在代码中更改后也能更新,但我遇到的问题是,除非是布尔值,否则我无法更改值,我搜索了很多资料,但没有找到解决方案。

以下是我定义属性的代码:

    [Description("Defines the Position on the screen")]
    public Vector2 screenpos { get;  set; }
    Vector2 WorldPos;
    [Description("Defines the texture of the selected tile")]
    public string texture { get;  set; }
    [Description("Defines if the player can collide with this tile")]
    public bool IsCollidable { get;  set; }
    [Description("Defines on what layer this tile is drawn (1-3)")]
    public int Layer { get;  set; }
    [Description("Shows if the tile is currently visible on the screen")]
    public bool OnScreen { get;  private set; }

我可以编辑IsCollidable,如果我从OnScreen的set中删除private,我也可以编辑它,但我不能编辑其他任何内容。噢,如果你能用更简单的语言回答我的问题,我会很感激的,因为我不是很有经验的程序员。提前感谢。

4个回答

5
大多数具有公共属性(可读写)的标准类型都应该是可编辑的。
如果 Vector2 相当简单,并且你只想在 PropertyGrid 中扩展它,则:
[Description("Defines the Position on the screen")]
[TypeConverter(typeof(ExpandableObjectConverter))]
public Vector2 screenpos { get;  set; }

如果Vector2是您自己的代码,那么您也可以装饰Vector2本身,并且它将适用于所有属性:
[TypeConverter(typeof(ExpandableObjectConverter))]
public {class|struct} Vector2 {...}

还有一个技巧可以对你无法控制的类型进行此操作;在应用程序启动时运行:

TypeDescriptor.AddAttributes(typeof(Vector2),
    new TypeConverterAttribute(typeof(ExpandableObjectConverter)));

1

0
我遇到的问题是,除非它是布尔值,否则我无法更改值。
我在您的代码中没有看到任何解释这一点的内容。您不需要做任何特殊的事情来使属性网格中的int或string属性可编辑,如此最小化的示例所示:
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication13
{
   static class Program
   {
      [STAThread]
      static void Main()
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
      }
   }

   public class Test
   {
      public string StringProperty { get; set; }
      public int IntProperty { get; set; }
      public bool BoolProperty { get; set; }
   }

   class MainForm : Form
   {
      public MainForm()
      {
         var propertyGrid = new PropertyGrid() { Dock = DockStyle.Fill };
         this.Controls.Add(propertyGrid);
         propertyGrid.SelectedObject = new Test();
      }
   }
}

使用上述代码,我可以编辑所有三个属性。您如何确定您“无法更改值”?您究竟看到了什么?


我将它们视为常规属性网格,没有任何灰色的内容,我可以移动文本光标等,但如果我键入(字母或数字),则不会发生任何事情。 - Alexander Karsten

0

我解决了,我在Form1构造函数中设置了this.KeyPreview = true;,通过删除它,我可以解决这个问题。 感谢您的所有帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接