How to 'merge' a XAML file and its code-behind with Visual Studio How to 'merge' a XAML file and its code-behind with Visual Studio wpf wpf

How to 'merge' a XAML file and its code-behind with Visual Studio


You need to edit the .csproj file. Find the <Compile> element for MyTemplate.cs, and add a <DependentUpon> element under it:

<Compile Include="MyTemplate.cs">  <DependentUpon>MyTemplate.xaml</DependentUpon></Compile>

See this blog post: make a project item a child item of another


This isn't an answer to your initial question, but to this:

In that case, please explain how to add an event handler to a template without using code-behind

You can do this with a ViewModel and an ICommand class.

First you need to create your ViewModel class, make this public and non static with a parameter-less constructor.

Then create another class which implements the ICommand interface:

public class Command : ICommand{    public void Execute(object parameter)    {        //this is what happens when you respond to the event    }    public bool CanExecute(object parameter)    {        return true;    }    public event EventHandler CanExecuteChanged;}

Add an instance of your command class to your ViewModel class, make this private and expose it through a read-only property:

public class ViewModel{    private readonly ICommand _command = new Command();    public ICommand Command    {        get { return _command; }    }}

Add your ViewModel as a static resource, in your App.xaml file:

<Application.Resources>     <wpfApplication1:ViewModel x:Key="ViewModel"/></Application.Resources>

Set your DataContext of your XAML file to your ViewModel:

<Window DataContext="{StaticResource ViewModel}">

Now respond to your event by binding to the Command class:

<Button Click="{Binding Command}"></Button>

Boom, no code-behind. Hope this helps.


Another way is to:

  • Add/Create a new XAML file/item
  • Copy and paste the old .xaml and xaml.cs content to the new equivalent files
  • delete the separate files
  • rename the new file