2010-07-18 63 views
7

正如我在another post中所述,我有時會直接從後面的代碼中訪問控件。如果我這樣做,我的名字的控件,因爲我在CONTROLTEMPLATES和的DataTemplates做的還可以,我給他們的前綴PART_和我確切的名稱,例如...標記中的WPF控件的命名

<TextBox Name=」PART_UserName」 /> 

後,這是對付共同的WPF命名方案?以前我使用的前綴M_隨後描述...

<TextBox Name=」m_userName」 /> 

..因爲在現實中它的正是這一點,但我不喜歡它。 你覺得呢? 請注意,我不想討論是否使用MVVM。有些情況我不在乎。

回答

11

當您編寫可以重新設計的自定義控件時,將使用PART_<name>模式。這些是模板的強制部分的名稱,如果沒有它,控件就無法工作。這樣的名字通常與C#代碼[TemplatePart]屬性聲明:

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

    ... 
} 

所以,除非你正在編寫一個控制模板,沒有理由使用該命名模式。只要命名你的控件,只要它對你有意義。