在标记中命名WPF控件

HCL*_*HCL 7 wpf

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

<TextBox Name=”PART_UserName” />
Run Code Online (Sandbox Code Playgroud)

这是针对常见的WPF命名方案吗?以前我使用前缀m_后跟描述...

<TextBox Name=”m_userName” />
Run Code Online (Sandbox Code Playgroud)

..因为在现实中它正是这个,但我不喜欢它.你怎么看?请注意,我不想讨论是否使用MVVM.有些情况我不在乎.

Tho*_*que 11

PART_<name>编写可重新导入的自定义控件时,将使用该模式.这些是模板的强制部分的名称,没有它们,控件就无法工作.这些名称通常使用[TemplatePart]C#代码中的属性声明:

[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...
         ...
     }

    ...
}
Run Code Online (Sandbox Code Playgroud)

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