i前缀 wpf_WPF UI元素命名约定

Although Hungarian notation is considered bad practice nowadays, it is still quite common to encode the type in the name of user interface elements, either by using a prefix (lblTitle, txtFirstName, ...) or a suffix (TitleLabel, FirstNameTextBox, ...).

In my company, we also do this, since it makes code written by co-workers (or by yourself a long time ago) easier to read (in my experience). The argument usually raised against doing this -- you have to change the name of the variable if the type changes -- is not very strong, since changing the type of a UI element usually requires rewriting all parts of the code were it is referenced anyway.

So, I'm thinking about keeping this practice when starting with WPF development (hmmm... should we use the txt prefix for TextBlocks or TextBoxes?). Is there any big disadvantage that I have missed? This is your chance to say "Don't do this, because ...".

EDIT: I know that with databinding the need to name UI elements decreases. Nevertheless, it's necessary sometimes, e.g. when developing custom controls...

解决方案

Personally, I find that WPF changes the rules when it comes to this. Often, you can get away with little or no code behind, so having the prefixes to distinguish names makes things more confusing instead of less confusing.

In Windows Forms, every control was referenced by name in code. With a large UI, the semi-hungarian notation was useful - it was easier to distinguish what you were working with.

In WPF, though, it's a rare control that needs a name. When you do have to access a control via code, it's often best to use attached properties or behaviors to do so, in which case you're never dealing with more than a single control. If you're working in the UserControl or Window code-behind, I'd just use "Title" and "Name" instead of "txtTitle", especially since now you'll probably only be dealing with a few, limited controls, instead of all of them.

Even custom controls shouldn't need names, in most cases. You'll want templated names following convention (ie: PART_Name), but not actual x:Name elements for your UIs...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值