Gotcha: VB.NET classes and namespaces in XAML

One difference between XAML in a C# project and VB.NET projects is in specifying the x:Class of your XAML root element. For example, in a C# Window XAML file:

<Window 
    x:Class="BigBank.UI.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
    >
    <Grid>

    </Grid>
</Window>

By contrast, the VB.NET version must leave out the namespace:

<Window 
    x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
    >
    <Grid>

    </Grid>
</Window>

If you forget to make these changes, a typical error message you might encounter is "Name 'InitializeComponent' is not declared", or similar. This occurs because the generated VB.NET file to load the XAML is placed into a namespace different to the one of your code-behind, and thus the code behind can't find it's partial class which declares the method.

Where this becomes inconsistent is when you include other namespaces in your project, whereby you do need to use the fully qualified namespace:

<Window 
    x:Class="Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"           
    xmlns:me="clr-namespace:BigBank.UI.Controls" Title="Window1" Height="300" Width="300" 
    > 
    <Grid> 

    </Grid> 
</Window>

This issue typically comes up when converting VB.NET XAML files to C# projects or vice-versa.

vb.net xaml wpf silverlight
Posted by: Paul Stovell
Last revised: 04 Feb, 2012 05:20 AM History

Comments

11 Nov, 2009 09:38 PM

Thanks Paul, you just saved me some time.

Cheers, Daniel

Christian G&#252;nther
Christian Günther
07 Sep, 2010 09:53 AM

There is an issue, not realy belonging to the namespace problem, but for the VB.NET programmers writing a magellan app from scratch: remove the

StartupUri="MainWindow.xaml"

from your Application.xaml. Else there will be two windows showing up and/or you encounter an error message like "constructor for MainWindow.xaml not found".

No new comments are allowed on this post.