标记中 WPF 控件的命名 [英] Naming of WPF-Controls in Markup

查看:28
本文介绍了标记中 WPF 控件的命名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我在另一篇文章中所述,我有时会访问直接从背后的代码控制.如果我这样做,我会像在 ControlTemplates 和 DataTemplates 中一样命名控件,给它们前缀 PART_,然后我精确命名,例如……

As I stated in another post, I access at times controls direct from the code behind. If I do this I name the controls as I do also in ControlTemplates and DataTemplates, I give them the prefix PART_ and after that I precise the name, for example…

<TextBox Name="PART_UserName" />

这是否违反了常见的 WPF 命名方案?以前我使用前缀 m_ 后跟描述......

Is this against a common WPF naming scheme? Formerly I used the prefix m_ followed by the description…

<TextBox Name="m_userName" />

...因为实际上正是这个,但我不喜欢它.你怎么认为?请注意,我不想讨论是否使用 MVVM.有些情况我不关心.

.. because in reality its exactly this, but I don’t liked it. What do you think? Please note, I don’t want to discuss whether to use MVVM or not. There are situations I don’t care about.

推荐答案

模式 PART_ 用于编写可重新模板化的自定义控件.这些是模板必需部分的名称,没有这些名称,控件将无法工作.此类名称通常使用 [TemplatePart]属性:

The pattern PART_<name> is used when you write custom controls that can be retemplated. These are the names of mandatory parts of the template, without which the control cannot work. Such names are usually declared with a [TemplatePart] attribute in C# code :

[TemplatePart(Name = "PART_TextBox", Type = typeof(TextBox))]
[TemplatePart(Name = "PART_UpButton", Type = typeof(Button))]
[TemplatePart(Name = "PART_DownButton", Type = typeof(Button))]
public class NumericUpDown : Control
{
    ...

     protected override OnApplyTemplate()
     {
         base.OnApplyTemplate();

         // Find controls in the template
         TextBox textBox = Template.FindName("PART_TextBox", this) as TextBox;
         Button upButton = Template.FindName("PART_UpButton", this) as Button;
         Button downButton = Template.FindName("PART_DownButton", this) as Button;

         // Do something with the controls...
         ...
     }

    ...
}

因此,除非您正在编写控件模板,否则没有理由使用该命名模式.只需为您的控件命名您喜欢的任何名称,只要它对您有意义即可.

So unless you're writing a control template, there's no reason to use that naming pattern. Just name your controls whatever you like, as long as it makes sense for you.

这篇关于标记中 WPF 控件的命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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