I have a template defined in a XAML file named 'MyTemplate.xaml'. This template is using a code-behind file named 'MyTemplate.cs'.
Mytemplate.xaml:
<ResourceDictionary x:Class="Project.Templates.MyTemplate">
<DataTemplate ... />
</ResourceDictionary>
MyTemplate.cs:
namespace Project.Templates
{
public partial class MyTemplate : ResourceDictionary
{
...
}
}
In the Visual Studio Solution Explorer, these two files are side by side. What I would like to do is to put these two files together, just like with a Control and its code-behind.
What I have:
What I would like to have:
What is the best way to do that? Thank you.
If you drag-and-drop the . xaml file from Windows Explorer into the Solution Explorer window, it will automatically add the . xaml with the code-behind . cs file.
To open the XAML Designer, right-click a XAML file in Solution Explorer and choose View Designer. to switch which window appears on top: either the artboard or the XAML editor.
XAML is a new descriptive programming language developed by Microsoft to write user interfaces for next-generation managed applications. XAML is the language to build user interfaces for Windows and Mobile applications that use Windows Presentation Foundation (WPF), UWP, and Xamarin Forms.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With