I have a new VB.Net WPF application. The MainWindow.xaml contains nothing more than a single ‘test’ button:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Test"
Name="btnTest" />
</Grid>
</Window>
The Application.xaml is untouched:
<Application x:Class="Application"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
The code behind is shown here. All I did was double click the button so the event handler is added automatically. I have also added the MainWindow to the View namespace.
Namespace View
Class MainWindow
' A test button on the main window
Private Sub btnTest_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles btnTest.Click
MessageBox.Show("Hello world!")
End Sub
End Class
End Namespace
When I build this it doesn’t compile. Error message that I get is:
Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
When I remove the MainWindow from the View namespace everything is fine. So clearly the namespace is an issue. Can I add a Window to a namespace and do I need to change something else in the application to make it work?
You are breaking the partial class when you are putting it in a namespace. In addition to moving the VB.NET code behind to the namespace, you need to move the
x:Classattribute as well:And
Visual Studio generates a partial VB.NET class that is a partial with your code behind. Since you moved the code behind to another namespace, it is no longer a partial with what Visual Studio generates.