Visual Basic: Using XML Literals To Declare Controls

If you’re used to writing code in Visual Basic, you know that with XML Literals you can embed any kind of XML markup in your code; this rule includes XAML markup. For instance, you can declare a button as follows:

Dim testControl = <Button Width="100" Height="50" Name="Button1">Test</Button>

To make this line usable in the application, you need to import the XAML default namespaces:

Imports <xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/ presentation">Imports <xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml">

You can then easily parse the control definition by invoking the XamlReader.Parse method as follows:

Dim myButton = CType(System.Windows.Markup.    XamlReader.Parse(testControl.ToString), ...

Get Hidden WPF: Secrets for Creating Great Applications in Windows Presentation Foundation now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.