To make this possible, the control must include a
XAML Name attribute. In the previous example, the Grid control does not include a Name
attribute, so you won??™t be able to manipulate it in your code-behind file.
Here??™s how you can attach a name to the Grid:
6
7 CHAPTER 2 n XAML 30
You can make this change by hand in the XAML document, or you can select the grid in
the Visual Studio designer and set the Name property using the Properties window.
Either way, the Name attribute tells the XAML parser to add a field like this to the automatically
generated portion of the Window1 class:
Friend WithEvents grid1 As System.Windows.Controls.Grid
Now you can interact with the grid in your Window1 class code by using the name grid1:
MessageBox.Show(String.Format("The grid is {0}x{1} units in size.", _
grid1.ActualWidth, grid1.ActualHeight))
This technique doesn??™t add much for the simple grid example, but it becomes much more
important when you need to read values in input controls such as text boxes and list boxes.
The Name property shown previously is part of the XAML language, and it??™s used to help
integrate your code-behind class. Somewhat confusingly, many classes define their own Name
property. (One example is the base FrameworkElement class from which all WPF elements
derive.
Pages:
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128