向非用户定义的类添加属性
我们一直使用控件,例如按钮,有时我们可能想向该按钮添加一些自定义属性。例如 numberOfTimesClicked 等。我目前正在使用 GridViewColumnHeader,我想将属性 columnIndex 添加到该类。我知道我可以使用其他方法跟踪列,但我只是想知道我们是否可以向类添加额外的属性。例如,我在考虑继承。如果我创建一个新类并继承我想要添加新属性的类(在我的例子中为 GridViewColumnHeader),那么我认为这应该可行,但由于某种原因,每当我执行以下操作时,我都会在代码中遇到错误:
private class MyGridViewColumnHeader : GridViewColumnHeader
{
public int propertyThatIWantToAdd { get; set; }
}
从现在开始,如果我从 MyGridViewColumnHeader 类而不是 GridViewColumnHeader 类实例化对象,但出现错误。使用继承来实现这一点有什么问题吗?
We use controls all the time for example a button and sometimes we may want to add some custom properties to that button. For example numberOfTimesClicked etc. I am currently working with GridViewColumnHeader and I would like to add the property columnIndex to that class. I know I can keep track of the columns with other methods but I am just curios to know if we can add extra properties to classes. For example I was thinking about inheritance. If I create a new class and inherit from the class that I want to add new properties (in my case GridViewColumnHeader) then I think that should work but for some reason I get errors in my code whenever I do something like:
private class MyGridViewColumnHeader : GridViewColumnHeader
{
public int propertyThatIWantToAdd { get; set; }
}
from now on if I instantiate objects from MyGridViewColumnHeader class instead of GridViewColumnHeader class I get errors. What is wrong with using inheritance to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要使用
sender
对象进行转换,而是使用And 在该对象上进行工作。如果您需要了解 RoutedEventArgs 内部的内容,请查看 MSDN
Instead of casting the
sender
object useAnd do your work on that object. If you need to know what is inside the
RoutedEventArgs
have a look on MSDN您应该将类设为
public
,private
修饰符仅允许用于内部类。另外,如果您想,您应该使用 依赖属性 而不是普通属性访问 XAML 中的属性。
You should make the class
public
, theprivate
modifier is only allowed for inner classes.Also you should use Dependency Properties instead of normal Properties, if you want to access the property in XAML.