1

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.

Abbas
  • 14,186
  • 6
  • 41
  • 72
Jim B
  • 8,344
  • 10
  • 49
  • 77
  • 1
    Did you try removing code behind? Why don't you comment out that InitializeComponent(); line and see what happens? – paparazzo Mar 12 '12 at 14:32

4 Answers4

9

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.

Paul Stovell
  • 32,377
  • 16
  • 80
  • 108
2

No! InitializeComponent() actually creates all the controls defined in the XAML file, and hence is very necessary.

See more info here: What does InitializeComponent() do, and how does it work in WPF?

Community
  • 1
  • 1
Jackson Pope
  • 14,520
  • 6
  • 56
  • 80
1

I don't believe you can remove it. Specifically, the InitializeComponent() function needs to be called.

tier1
  • 6,303
  • 6
  • 44
  • 75
0

You can't remove it. It initializes your Window (all buttons, labels, etc.).

Michal B.
  • 5,676
  • 6
  • 42
  • 70