我已经使用一些其他选项实现了自定义按钮控件。并将我的自定义按钮添加到表单中。当我设置Form.Acception是添加的自定义按钮,然后我想在Button中进行一些自定义。我想在自定义按钮类实现中自定义按钮外观,当它标记为Form的AcceptButton时。
任何人都建议我怎么知道按钮被标记为Button类中表单的AcceptButton?
答案 0 :(得分:0)
<强> WRONG:强>
protected override void OnLoad(EventArgs e) { base.OnLoad(E); if(((Form)this.TopLevelControl).AcceptButton == this) .... }
<强> UPD:强>
public class MyButton : Button
{
public override void NotifyDefault(bool value)
{
if (this.IsDefault != value)
{
this.IsDefault = value;
}
if (IsDefault)
{
this.BackColor = Color.Red;
}
else
{
this.BackColor = Color.Green;
}
}
}
答案 1 :(得分:-1)
您可以遍历父级以通过其基类Control
的父属性查找表单:
public partial class MyButton : Button
{
public MyButton()
{
InitializeComponent();
}
private Form CheckParentForm(Control current)
{
// if the current is a form, return it.
if (current is Form)
return (Form)current;
// if the parent of the current not is null,
if (current.Parent != null)
// check his parent.
return CheckParentForm(current.Parent);
// there is no parent found and we didn't find a Form.
return null;
}
protected override void OnCreateControl()
{
base.OnCreateControl();
// find the parent form.
var form = CheckParentForm(this);
// if a form was found,
if (form != null)
// check if this is set as accept button
if (this == form.AcceptButton)
// for example, change the background color (i used for testing)
this.BackColor = Color.RosyBrown;
}
}
由于递归,当Button放在Panel上时它也可以工作。
注意:必须在调用OnCreateControl 之前设置接受按钮(例如,在表单的构造函数中)
经过一些googling我发现了一个标准实现:
您还可以使用:this.FindForm();
public partial class MyButton : Button
{
public MyButton()
{
InitializeComponent();
}
protected override void OnCreateControl()
{
base.OnCreateControl();
var form = FindForm();
if (form != null)
if (this == form.AcceptButton)
this.BackColor = Color.RosyBrown;
}
}
C#6.0中的事件更短:
public partial class MyButton : Button
{
public MyButton()
{
InitializeComponent();
}
protected override void OnCreateControl()
{
base.OnCreateControl();
if (this == FindForm()?.AcceptButton)
this.BackColor = Color.RosyBrown;
}
}
<强> \ O / 强>