How to Load XAML Files dynamically at runtime without compiling your WPF XAML code?

Sometimes, you need to add controls to your WPF window at runtime. This can be done easily within WPF application as it enables you to display uncompiled XAML code. The below example demonstrates this feature by loading a button at runtime from an XML file and wiring up a click event to it to display a message when clicked.


public Window1()
{
  InitializeComponent();
  LoadRuntimeControls();
}

private void myButton_Click(object sender, RoutedEventArgs e)
{
  MessageBox.Show("I have been clicked");
}

private void LoadRuntimeControls()
{
  //Load button from XML file
  FileStream fileStream = new FileStream(@"c:\RuntimeContent.xml", FileMode.Open);
  DependencyObject dependencyObject = XamlReader.Load(fileStream) as DependencyObject;
  this.Content = dependencyObject;

  //Find the button and wireup a click event
  Button myButton = LogicalTreeHelper.FindLogicalNode(dependencyObject, "btnOnTheFly") as Button;
  myButton.Click+=new RoutedEventHandler(myButton_Click);
}

Please note that loading XAML dynamically is not as efficient as compiling it. However, sometimes, it is necessary to load it dynamically at runtime.

How to refernce a Namespace in XAML code?

XAML has a special format for referncing namespaces. In order to refernce a  namespace that is not included in the default WPF namespace you will have to do it in the following format.

 

First, refernce the namespace in your code in the following format:

xmlns:Prefix=”clr-namespace:Namespace;assembly=AssemblyName

Second, use the your chosen prefix in declaring your objects in the following format:

< Prefix:YourObject …. / >

 

How to insert white spaces in your XAML property value?

XAML language is treated as XML, it ignores all white spaces. Therefore, if you need to add a value that contains white spaces at the end of it for some reason, it would be ignored. In order to overcome this problem you can use thexml:space=”preserve”  in your element declaration.

<Button x:Name="btn" xml:space="preserve">Click ME      </Button>

How to insert special characters content in XAML?

Suppose you want to have a button with that displays < Click Here >. Doing this the traditional way

<Button x:Name="btn"><Click Here></Button> 

will drive you to troubles becuase the XAML parser will think that you want to create an element called Click with an attribute called here. Therefore, you need to encode the special characters in your code.

Less than (<) &lt;

Greater than (>) &gt;

Quotation mark (“) &quot;

Ampersand (&) &amp;

Therefore, you will instead need to write your statement as follows:

<Button x:Name=”btn”> &lt;Click Here&gt; </Button>

Special Character Character Entity
Less than (<) &lt;
Greater than (>) &gt;
Ampersand (&) &amp;
Quotation mark (“) &quot

Want to set your XAML property value to an object?

Do you want to set your XAML property value to an object, the answer is Markup Extensions. Markup Extensions helps you set XAML property values to an object or may be dynamically at runtime.

For example, suppose you want to set the the Foreground property for a TextBlock control to the static property SystemColors.ActiveCaptionBrush. You can achieve this through the code behind through the following statement:

textBlock.Foreground = SystemColors.ActiveCaptionBrush;

Alternatively, you can do this through the XAML editor directly using the following statement:

< TextBlock x:Name="textBlock" Foreground="{x:Static SystemColors.ActiveCaptionBrush}" / >

Markup extensions is used through the syntax {MarkupExtensionClass Argument}. In this case, the
markup extension was a StaticExtension class, SystemColors.

MarkupExtension must be enclosed within braces { }

WPF Performance on Windows Vista/ Windows XP

WPF provides better performance under the Windows Vista operating system, where it can take advantage of the new Windows Vista Display Driver Model (WDDM). WDDM offers several important enhancements beyond the Windows XP Display Driver Model (XPDM). Most importantly, WDDM allows several graphics processing
unit (GPU) operations to be scheduled at once, and it allows video card memory to be paged to normal system memory if you exceed what’s available on the video card. WPF offers some sort of hardware acceleration to all WDDM (Windows Vista) drivers and to XPDM (Windows XP) drivers that were created after November 2004, which is when Microsoft released new driver development guidelines. Of course, the level of support differs. When the WPF infrastructure first starts up, it evaluates your video card and assigns it a rating from 0 to 2.

WPF is intelligent to use hardware optimizations where possible, but it has a software fallback for everything. So if you run a WPF application on a computer with a legacy video card, the interface will still appear the way you designed it. Of course, the software alternative may be much slower, so you’ll find that computers with older video cards won’t run rich WPF applications very well, especially ones that incorporate complex animations or other intense graphical effects.

The difference between Margin and Padding properties

Margin and Padding are two similar layout concepts that are often confused. Margin represents the amount of space around the outside of the element. This space ensures that the Element has room between it and neighboring elements. Padding functions differently. It is present on elements that inherit from Control  and allows the control to specify an amount of space inside itself. This inner space separates the control from its own content.  Take for example the Button control. The space inside the Button, around its text, that prevents the Button‘s border from shrinking to the size of its contents. Take a look at the below diagram which illustartes the differenece more.

marginandpadding