确保设置 UserControl 上的属性的好方法? [英] Good way to ensure that a property on a UserControl gets set?

查看:26
本文介绍了确保设置 UserControl 上的属性的好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们的 UserControl 需要设置某些属性才能有用,那么确保设置这些属性的最佳方法是什么?即使只是作为给自己和/或亲密同事的便笺.

If our UserControl requires certain properties are set for it to be useful, what's the best way to ensure they are set? Even if just as a note to self and/or close colleagues.

我们已经尝试过使用 Initialize 方法,但这已经让我们措手不及,因为我们忘记在一个实例中更新 Initialize,稍微改变了设计.

We've tried using an Initialize method, but that's already caught us out because we forgot to update the Initialize in one instance, having slightly changed the design.

另一个想法是使用合理的默认值,这样如果我们忘记设置它,那么至少有一些有用的东西.但在这种情况下,没有一个有用的默认值.我真的想要一个给自己的强烈提示来提醒我每次创建控件实例时都需要设置一些东西.

The other idea is to use a sensible default, so that if we forget to set it then there's at least something useful there. But in this case there isn't a useful default. I really want a strong note to self to remind me there's something here that needs to be set every time I create an instance of the control.

推荐答案

您无法在设计师级别强制执行任何操作,也没有我已完成设计"触发器.但当然是在运行时,尽早抛出异常:

Nothing you could enforce at the designer level, there is no "I'm done designing" trigger. But certainly at runtime, just throw an exception at the earliest possible moment:

protected override void OnCreateControl(EventArgs e) {
    if (!DesignMode && !mumbleAssigned) 
        throw new InvalidOperationException("Oops, Mumble property wasn't set");
    base.OnCreateControl(e);
}

如果您实现 OnPaint() 方法,您可以使其更加微妙.和简单的 e.Graphics.DrawText 一个提醒.在属性设置器中调用 Invalidate().这在设计时有效.

You could make it more subtle if you implement the OnPaint() method. And simply e.Graphics.DrawText a reminder. Call Invalidate() in the property setter. This works at design time.

这篇关于确保设置 UserControl 上的属性的好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆