WPF C# Button Event Handler Not Working - c#

I am having a problem getting and event handlers to work for a button. I am using Visual Studio 2015. My code and error is below:
XAML:
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication1" mc:Ignorable="d" Title="MainWindow" Height="500" Width="983.334">
.
.
.
<Button x:Name="Button1" Content="Database" HorizontalAlignment="Left"
Margin="10,427,0,0" VerticalAlignment="Top" Width="99"
Click="Button1_Click"/>
Code behind:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Test");
}
}
}
Error:
CS1061 'MainWindow' does not contain a definition for 'Button1_Click' and no extension method 'Button1_Click' accepting a first argument of type 'MainWindow' could be found (are you missing a using directive or an assembly reference?)
Whenever I add a button and click on the event handler section this is what I see: The document item had no code-behind file. Add a code-behind file and a class definition before adding event handlers.
Any help would be appreciated.

It works for me for the following XAML
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication1" mc:Ignorable="d" Title="MainWindow" Height="500" Width="983.334">
<Button x:Name="Button1" Content="Database" HorizontalAlignment="Left"
Margin="10,427,0,0" VerticalAlignment="Top" Width="99" Click="Button1_Click"/>
</Window>
and the following code behind file
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Test");
}
}
which is exactly what you have.
Have you tried rebuilding the solution?

Sound like the Event isn't registered in the page, click on your button and check the events tab to see if it's registered... check this image:
https://postimg.org/image/5q6nvac7b/

Related

Cannot create an instance of Usercontrol when subscribing an event

There are other threads on the topic but I did not find any that are related to my specific problem.
In Visual Studio 2017, I have a situation when the XAML designer prompt an error even though nothing strange seems to be present.
Basically, to reproduce the problem, consider those two files,
MainWindow.xaml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TabControl Background="White">
<TabItem Header="TEST" Width="60">
<local:UserControl1/>
</TabItem>
</TabControl>
</Grid>
</Window>
Usercontrol1.xaml.cs
namespace WpfApp1
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
App.Current.MainWindow.Closing += window_Closing;
}
void window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
}
}
}
Note that I did not include the content of Usercontrol1.xaml because it is not relevant here. It can be an empty UserControl.
Now, the designer shows the Error
Cannot create an instance of "Usercontrol1".
It is strange since when starting the application, everything is working fine. This is easily reproducible by creating a new WPF app and creating the same pattern shown above.
NOTE
I tried removing the subscription
App.Current.MainWindow.Closing += window_Closing;
And it removes the error. So, it is the cause, but why ?
App.Current will be null while in DesignMode.
You can check for IsInDesignMode to prevent running this code. Like,
public UserControl1()
{
InitializeComponent();
if(!DesignerProperties.GetIsInDesignMode(this))
App.Current.MainWindow.Closing += window_Closing;
}
Related post in MSDN blog.

System.TypeInitializationException when changing MainWindow startupUri WPF

I am trying to change the MainWindow location in a WPF application from the default startup URI: MainWindow.xaml to Views\MainWindow.xaml. where Views is a folder created inside the project folder.
Uri: this.StartupUri = new System.Uri(#"Views\MainWindow.xaml", System.UriKind.Relative);
I changed the uri and then the application breaks with the following error:
An unhandled exception of type 'System.TypeInitializationException'occurred in PresentationFramework.dll
Additional information: The type initializer for 'System.Windows.Application' threw an exception.
I placed breakpoints and try-catch blocks in the Main method,the InitializeComponent method and the MainWindow constructor to no avail.It crashes and i can't catch the exception.
Main:
public static void Main() {
try
{
wpfTest.App app = new wpfTest.App();
app.InitializeComponent();
app.Run();
}catch(Exception ex)
{
Console.WriteLine(ex.InnerException.Message);
}
}
Does the startupUri have to be changed somewhere else too?It has only one reference :the one in the InitializeComponent method.
To move the MainWindow to a Views folder (namespace), you have to follow this steps
Change the class name in MainWindow.xaml
<Window x:Class="WpfApp1.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
</Grid>
</Window>
Modify the namespace in MainWindow.xaml.cs
namespace WpfApp1.Views
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
Modify the App.xaml
<Application x:Class="WpfApp1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
StartupUri="Views/MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
Move MainWindow.xaml to the Views folder
And thats it.
It does not matter which one you do first/last, but you have to do all of them.

The 'InitializeComponent' fails compiling WPF with csc.exe

I know that this problem was posted several times on StackOverflow. And I already checked these posts but can't figure out the error in my program.
I downloaded a simple WPF HelloWorld program and tried to compile it with the command-line tool:
csc.exe /out:WPFApplication.exe /target:winexe App.cs MainWindow.cs /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationFramework.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationCore.dll"
But I only got the error message "The name 'InitializeComponent' does not exist in the current context".
Here's the App.cs:
using System.Windows;
namespace HelloWorld
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
App.xaml:
<Application x:Class="HelloWorld.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:HelloWorld"
StartupUri="MainWindow.xaml"/>
MainWindow.cs:
using System.Windows;
namespace HelloWorld
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
and MainWindow.xaml:
<Window x:Class="HelloWorld.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:HelloWorld"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" Icon="app.ico">
<Grid>
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center">
Hello, World!
</TextBlock>
</Grid>
</Window>

Weird Unload Behaviour - WPF Window

I have a simple WPF application with a MainWindow. Set up an unloaded event in the code behind. Set the MainWindow as the startup uri. Unloaded is not triggered when the window is closed. Create a second window - NotMainWindow with a single button click.
In the button click event, call MainWindow. Close MainWindow and unloaded is triggered. Why the difference in behaviour? What I am trying to get at is, how do I get some kind of unloaded event every single time?
<Window x:Class="WpfApplication2.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" Unloaded="Main_Unloaded">
<Grid>
</Grid>
</Window>
private void Main_Unloaded(object sender, RoutedEventArgs e)
{
}
<Window x:Class="WpfApplication2.NotMainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="NotMainWindow" Height="300" Width="300">
<Grid>
<Button Content="Show Main" Height="25" Margin="10" Width="70" Click="Button_Click" />
</Grid>
</Window>
private void Button_Click(object sender, RoutedEventArgs e)
{
MainWindow win = new MainWindow();
win.Show();
}
<Application x:Class="WpfApplication2.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="NotMainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
Based on your comments I understand the scenario you're talking about. This is a known issue that unloaded is not called when shutting down the application (e.g. last window is closed).
If you just want to know when the window is closed use the Closing event:
public MainWindow()
{
this.Closing += new CancelEventHandler(MainWindow_Closing);
InitializeComponent();
}
void MainWindow_Closing(object sender, CancelEventArgs e)
{
// Closing logic here.
}
If you want to know when the last window is closed, e.g. your application is shutting down, you should use ShutdownStarted
public MainWindow()
{
this.Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;
InitializeComponent();
}
private void Dispatcher_ShutdownStarted( object sender, EventArgs e )
{
//do what you want to do on app shutdown
}

Setting <Window.DataContext> in XAML

I followed a very simple MVVM example as a basis for my program. The author had one code behind instruction he used in the main page to set the DataContext. I'm thinking I should be able to do this in the XAML instead. The MainWindowViewModel is in a directory ViewModels. The code behind works.
namespace RDLfromSP
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModels.MainWindowViewModel();
}
}
}
I can't seem to find the right combo to set it instead in the XAML
<Window x:Class="RDLfromSP.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300" >
<Window.DataContext>
<local:ViewModels.MainWindowViewModel />
</Window.DataContext>
Thanks in advance for your help
You'll need an xml namespace mapping to the ViewModels namespace. Once you add that, it would be:
<Window.DataContext>
<vms:MainWindowViewModel />
</Window.DataContext>
(This is assuming you map vms to the appropriate namespace.)
This should look just like your current namespace mapping for local:, but called vms: with the appropriate namespace specified.

Categories

Resources