#1,214 – Naming Scheme for XAML Elements

Although XAML elements do not require a name, it’s sometimes useful to name them for debugging purposes–e.g. when using Visual Studio’s Live Visual Tree.

Below is a modest proposal for a naming convention for various WPF controls.

  • AccessText – at
  • Border – brd
  • BulletDecorator – bd
  • Button – btn
  • Calendar – cal
  • Canvas – cnv
  • CheckBox – chk
  • ComboBox – cbo
  • ContextMenu – ctx
  • DataGrid – dg
  • DatePicker – dat
  • DockPanel – dp
  • Expander – exp
  • Frame – fr
  • Grid – grd
  • GridSplitter – gsp
  • GroupBox – grp
  • Hyperlink – hyp
  • Image – img
  • InkCanvas – ikc
  • InkPresenter – ikp
  • Label – lbl
  • ListBox – lb
  • ListView – lv
  • MediaElement – me
  • Menu – mnu
  • NavigationWindow – nw
  • Page – pg
  • Panel – pnl
  • PasswordBox pwd
  • Popup – pop
  • ProgressBar – pb
  • RadioButton rdo
  • ResizeGrip – rgr
  • RepeatButton rpt
  • RichTextBox – rtb
  • ScrollBar – sb
  • ScrollViewer – sv
  • Separator – sep
  • Slider – sli
  • StackPanel – sp
  • StatusBar – stb
  • TabControl – tab
  • TabItem – tbi
  • TextBlock – tb
  • TextBox – txt
  • Thumb – th
  • ToolBar – tbr
  • ToolTip – tt
  • TreeView – tv
  • Viewbox – vb
  • VirtualizingStackPanel – vsp
  • Window – win
  • WrapPanel – wp

You could certainly go too far in naming controls in a WPF application. Instead of naming every single control, it’s probably more sensible to name a subset of controls, providing names when it makes sense.

#1,213 – Why You May Want to Name XAML Elements

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.

#706 – Dragging User Interface Elements Between Applications

You can drag user interface elements between WPF applications using drag-and-drop.  To do this, you read the XAML for the portion of the logical tree that you want to drag and specify XAML as your data format.

The example below shows how to drag a StackPanel and everything in it from one application to another.

On the drag side, we use a XamlWriter object to store all of the XAML into a string.

        private void StackPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string xaml = XamlWriter.Save(e.Source);
            DataObject data = new DataObject(DataFormats.Xaml, xaml);

            DragDrop.DoDragDrop((DependencyObject)e.Source, data, DragDropEffects.Copy);
        }

On the drop side, we use a XamlReader to load the data back into the application.  In this example, we set the StackPanel as the main content for the Window that we’re dragging it to.

        private void Window_Drop(object sender, DragEventArgs e)
        {
            string xaml = (string)e.Data.GetData(DataFormats.Xaml);
            this.Content = XamlReader.Load(new XmlTextReader(new StringReader(xaml)));
        }

706-001
706-002
706-003

#538 – XAML End Tags Are Automatically Added as Needed in Blend

When you first add an element to your user interface in Blend using one of the buttons on the tools panel, the corresponding XAML element does not typically hand an end tag.

For example, in the image below, we have a StackPanel element without an end tag (<StackPanel/>), rather than paired with an end tag (<StackPanel></StackPanel>).

If you now add a child element to the StackPanel using one of the buttons on the tools panel, Blend will automatically add the required end tag.

If you later delete the Button using the Objects and Timeline panel, removing all child elements from the StackPanel, the end tag is automatically removed.

#287 – Adding Controls to a Window in Blend by Editing XAML

You can add a WPF control to a window by using the design view editor in Blend.  You add the control by dragging and dropping it onto a design surface.

You can also add a control by editing the XAML directly while in the design view editor in Blend.

To open the design view editor for a particular window, double-click the associated .xaml file in the Projects window.

The design view editor will open, with the design surface showing and the XAML hidden.

Change the editor to be XAML-only or split screen by clicking on the appropriate icon in the upper right corner of the tab that shows the design surface.

 

If you choose Split, the XAML editor will appear in the lower half of the screen.

You can then enter or edit XAML directly in the XAML editor.

#286 – Adding Controls to a Window in Visual Studio by Editing XAML

You can add a WPF control to a window by using the design view editor in Visual Studio.  You add the control by dragging and dropping it onto a design surface.

You can also add a control by editing the XAML directly while in the design view editor in Visual Studio.

To open the design view editor for a particular window, double-click the associated .xaml file in the Solution Explorer.

The editor will show up as a split screen, with the design surface on the top and the XAML that defines the window contents below.

You can add a control by manually entering XAML in the lower window.  Here’s the XAML for a simple button.

As you enter XAML in the lower half of the editor, the design surface in the top half of the window will update to reflect the changes to the XAML.

#157 – You Can Set Standard CLR Properties from XAML

If you create a custom class, you can instantiate instances of that class from XAML by adding the object to a resource dictionary.

    <Window.Resources>
        <m:Person x:Key="perBill" FirstName="William" LastName="Shakespeare" />
    </Window.Resources>

You might wonder whether your properties have to be WPF dependency properties in order to set their values from XAML.  It turns out that the properties on the custom class do not have to be dependency properties in order to be set from XAML.  They can be standard CLR properties.

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Person()
        {
        }
    }