将自定义属性添加到常见控件问题
我想知道是否有更好的方法将接口实现到自定义控件中。 我正在自定义按钮控件中实现一个接口,为了引用已实现的属性,我需要将按钮转换为接口类型才能到达它。
有没有办法直接引用呢?我是否需要在按钮类中创建一个扭曲器属性,以将其公开给外界?
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;
}
}
}
I'll like to know if there better way to implement Interface into a custom control.
I'm implementing a Interface in a custom button control, and to refer to the implemented property I need to convert the Button to the interface type to reach it.
Is there a way to refer to it directly? Do I need to create a warper property in the button class, to expose it to outside world?
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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎希望接口存储设置的值。接口只是类必须实现其所有成员的契约。即使您注释掉引发错误的行,您也会收到编译时错误,表明您的
MyButton
类未实现MyInterface
的所有成员。您需要在
MyButton
类上实现string MyProp
。但是,如果您实际上想要做的是在多个类之间共享单个属性,您可以考虑使用基类:
--
It appears that you're expecting the interface to store the value set. An interface is just a contract that the class must implement all of its members. Even if you comment out the line that is throwing an error you will get a compile-time error that your
MyButton
class doesn't implement all members ofMyInterface
.You need to implement
string MyProp
on yourMyButton
class.However, if what you're actually trying to do is share a single property between multiple classes, you may consider using a base class instead:
--