#1,213 – Why You May Want to Name XAML Elements
July 16, 2017 2 Comments
In the days of Win Forms, we had to name every user interface element because the name is how we referenced the element when setting initial properties and then working with the element from code-behind.
In WPF, most developers have (hopefully) trained themselves to not bother with naming elements. Ideally, all interaction with a control is done through the use of commands and data binding, which means that there is then no need to ever access a control from code-behind.
Having said that, there is one valid use case for naming XAML elements in WPF. When you use a debugging tool that shows you the visual tree of an application, it’s helpful to have your elements named, so you can figure out what’s what.
Below is a XAML fragment for a simple WPF application. Note that I’ve named some of the elements (I’m not bothering to name simple labels).
<Grid x:Name="grdMain" Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Button x:Name="btnPressMe" Grid.Row="0" Grid.Column="0" Margin="10" Command="local:SomeViewModel.PressMeCommand" Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" Padding="10,5"/> <TextBlock x:Name="txbPressResults" Grid.Row="0" Grid.Column="1" Margin="10" Text="{Binding PressResults}"/> <TextBlock Grid.Row="1" Grid.Column="0" Text="Say something:"/> <TextBox x:Name="txtYourText" Grid.Row="1" Grid.Column="1" Text="{Binding YourText}"/> <TextBlock Grid.Row="2" Grid.ColumnSpan="2" Text="Gosh, I love this application"/> </Grid>
When I run the application, I can bring up Visual Studio’s Live Visual Tree and then explore the visual tree of the application. Notice the named elements in the visual tree, corresponding to the names given in the XAML.
Naming elements in this way can make debugging a bit easier when you’re navigating through the visual tree.
I would also remind another case when naming an element is useful. When you want to bind using “ElementName”.
And in terms of xaml readability I like to name some elements to remember what they stand for (this avoid the need of a comment). Feel free to read my blog post about Xaml here: https://ju2pom.github.io/WPF-journey-part1/
Pingback: Dew Drop - July 17, 2017 (#2521) - Morning Dew