Search code examples
wpfcode-behind

Do I need my code-behind file?


In my WPF app, all I have in my code-behind is the following:

public partial class MainWindow
{    
    public MainWindow()
    {
         InitializeComponent();
    }    
}

Can I completely remove the code-behind file from my project or does it have to stay there? My background is in web app development and I'm kind of relating this to a code-behind file with an empty Page_Load() method, which I would typically remove.


Solution

  • You can remove it, if you use one of these techniques:

    1: Remove the x:class declaration from the top of your XAML file, and find a different way to instantiate the object (e.g., you can't use new MainWindow(), but you can use XamlReader.Load and cast the result to a Window).

    or

    2: Use this approach:

    <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="300" Width="300">
      <StackPanel>
    
        <Button x:Name="mybutton">Hello</Button>
    
        <x:Code>
          <![CDATA[
          public MainWindow()
          {
            InitializeComponent();
    
            mybutton.Content = "Goodbye";
          }
          ]]>
        </x:Code>
      </StackPanel>
    </Window>
    

    This moves the InitializeComponent call into your XAML, so you can delete the codebehind file.