将Custom属性添加到公共控件问题
本文关键字:控件 问题 Custom 属性 添加 | 更新日期: 2023-09-27 18:23:53
我想知道是否有更好的方法将Interface实现到自定义控件中。我正在一个自定义按钮控件中实现一个接口,为了引用实现的属性,我需要将button转换为接口类型才能访问它
有没有一种方法可以直接引用它?我需要在按钮类中创建一个warper属性,以便将其暴露在外部世界吗?
namespace WorkBench
{
public partial class Form1 : Form
{
//Binding bind;
public Form1()
{
InitializeComponent();
MyButton btn = new MyButton();
btn.Myproperty = "";
((MyInterface)btn).MyProp = "";
btn.MyProp = "Not Available";//This give compile error, MyProp not defined
}
}
public class MyButton : System.Windows.Forms.Button, MyInterface
{
public string Myproperty
{
get { return null; }
set { }
}
string MyInterface.MyProp
{ get { return null; } set { } }
}
public interface MyInterface
{
void MyOtherPropoerty();
string MyProp
{
get;
set;
}
}
}
看起来您希望接口存储值集。接口只是一个约定,类必须实现它的所有成员。即使您注释掉了抛出错误的行,您也会得到一个编译时错误,即MyButton
类没有实现MyInterface
的所有成员。
您需要在MyButton
类上实现string MyProp
。
public class MyButton : System.Windows.Forms.Button, MyInterface
{
public string MyProperty
{
get { return null; }
set { /* ??? */ }
}
public string MyProp { get; set; } // <------ Implement string MyProp
}
然而,如果你实际上想在多个类之间共享一个属性,你可以考虑使用基类:
public class MyControlBase
: System.Windows.Forms.Button
{
public string MyProp { get; set; }
}
public class MyButton : MyControlBase
{
public string MyProperty { get; set; }
}
--
void Example()
{
var btn = new MyButton();
var property = btn.MyProperty;
var prop = btn.MyProp;
}