覆盖基类中定义的属性
我有类层次结构是这样的情况,
+---------------+ | UIElement | |---------------| +----------------------+ | ... | | My Windows Application | SomePropert{} | |----------------------| | |<---+ |+--------------------+| | | | ||MyUserControl || +---------------+ | ||--------------------|| +--------------+-----+ || || |FrameWorkElement | |+--------------------+| |--------------------| |//Want to use | | ... |<-+ |// SomeProperty; | +--------------------+ | | | +-----------+-+ | | |Control | | | |-------------| +----------------------+ | ... |<---+ +-------------+ | +-----------+---+ | UserControl | |---------------|<---+ | ... | | +---------------+ | +----------+-------+ | MyUserControl | |------------------| | SomeProperty{} | | //Want to override | | +------------------+
现在在我的应用程序(以及我可以导出此MyUserControl的所有其他应用程序)中,我可以设置由MyUserControl
类而不是UIElement
处理的MyUserControl
吗?
我现在正在通过创建一个MyUserControl对象并将其分配给我在xaml页面中添加的控件来做到这一点。所以现在看起来像这样,
MyUserControl newControl = new MyUserControl(); web = windowsPhoneControl11; //windowsPhoneControll1 is the //one that I added from toolbox. // ie, mycustomecontrol added from toolbox.
所以现在因为我使用’新’它会被覆盖。 但是当我导出这个控件时,我不能指望用户创建一个新对象并将其分配给在xaml页面中使用的控件。
那么有没有其他方法可以覆盖这一个属性,以便该属性的赋值由MyUserControl类而不是UIElement类处理? 我的意思是MyUserControl具有设置此属性的控件是我需要在分配之前检查一些值。 如果它不是至少预期值,那么我需要将其设置为默认值。
Ps:我很抱歉这么长的问题,但我无法更准确地表达,我无法找到与此相关的任何其他问题。 它是WindowsPhoneApp …不是普通的windowsapplication。
请原谅我,如果我错误地解释了这一点,但会做以下工作:
public class BaseClass { public int MyProperty { get; set; } } public class ChildClass : BaseClass { public new int MyProperty { get { return base.MyProperty; } set { if(DoYourCheckingStuff(value)) { base.MyProperty = value; } } } }
没试过这个。
虽然这感觉像是一种非常黑客的方式。 你实际上试图“控制”什么属性? 因为可能有更简单的方法来做到这一点。
示例:更改UserControl,使其宽度不能设置在100到200之间(尽管这可能是一个非常糟糕的方法),通过隐藏它的Width属性:
public class MyUserControl : UserControl { public new double Width { get { return base.Width; } set { if(!(value > 100 && value < 200)) base.Width = value; } } }
你可以像方法一样覆盖属性。
public new int Age() { get { return Age ?? 21; } set { Age = value; } }