有一个自定义属性取决于要在 WinForms 中正确初始化的其他系统属性的值。
让我给你举个例子。让我们创建一个WhateverButton: Button
具有自定义属性的类,MyExampleProperty
我们使用系统控件属性this.Height
,它来自控件的大小。
public classWhateverButton : Button { // 成员private int m_myExampleProperty; // 构造函数 public WhatButton () { m_myExampleProperty = 1; } // 属性 public int MyExampleProperty { get => m_myExampleProperty; set { m_myExampleProperty= value > (this.Height / 2F) ?1:值; } } // 每次Size改变时,更新属性 protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); m_myExampleProperty = m_myExampleProperty > this.Height / 2F ?1:m_myExampleProperty; } }
WhateverButton
在表单中添加(大小大于默认值)。WinForms 按字母顺序生成元素(按钮、标签、文本框等),例如:
this.buttonWhatever.Location = new System.Drawing.Point (413, 57); // L this.buttonWhatever.Margin = new System.Windows.Forms.Padding (3, 4, 3, 4); // M this.buttonWhatever.MyExampleProperty= 30; // M ... // 其他属性 this.buttonWhatever.Name = "myElement"; // N this.buttonWhatever.Size = new System.Drawing.Size (50, 80); // S this.buttonWhatever.Text = "我的元素"; // T
MyExampleProperty
通过表单 UI更改属性值后,它似乎有效,但在保存表单(Ctrl + S)后,属性返回到 1。
Debugging
可以发现每次保存 Form 时,所有元素都会按该顺序再次创建。当的时间MyExampleProperty
到达时,Size
尚未创建属性,该属性将采用默认Height
和Width
课程,并在属性的值将是错误的。如果我只是将 重命名为MyExampleProperty
将Size
在此示例中放置在属性之后的任何其他名称,它将起作用。也许我错过了一些我不知道要搜索的东西。
您的属性的问题在于,如果在设置属性时控件的高度不正确,则传递给 setter 的值将永远丢失。
因此,在 setter 中,您应该始终分配value
给支持字段,并检查getter 中的高度:
public int MyExampleProperty
{
get => m_myExampleProperty > (this.Height / 2F) ? 1 : m_myExampleProperty;
set
{
m_myExampleProperty = value;
}
}
这样,您甚至不需要处理SizeChanged
事件!
或者甚至更好,将其写为两个属性:
public int MyExampleProperty { get; set; }
public int MyExamplePropertyThatChangesWithSize =>
MyExampleProperty > (this.Height / 2F) ? 1 : MyExampleProperty;
...因为您没有获得刚刚设置的值的属性是非常出乎意料的,并且可能会令人困惑。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句