您需要编辑.csproj 文件。找到MyTemplate.cs的
<Compile>
元素,在其下添加一个<DependentUpon>
元素:
<Compile Include="MyTemplate.cs">
<DependentUpon>MyTemplate.xaml</DependentUpon>
</Compile>
请参阅此博客文章:使一个项目成为另一个项目的子项目
这不是对您最初问题的回答,而是对这个问题的回答:
在那种情况下,请解释如何在不使用代码隐藏的情况下将事件处理程序添加到模板
您可以使用 ViewModel 和 ICommand 类执行此操作。
首先,您需要创建您的 ViewModel 类,使用无参数构造函数使其公开且非静态。
然后创建另一个实现 ICommand 接口的类:
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;
}
将命令类的实例添加到 ViewModel 类,将其设为私有并通过只读属性将其公开:
public class ViewModel
{
private readonly ICommand _command = new Command();
public ICommand Command
{
get { return _command; }
}
}
在 App.xaml 文件中将您的 ViewModel 添加为静态资源:
<Application.Resources>
<wpfApplication1:ViewModel x:Key="ViewModel"/>
</Application.Resources>
将您的 XAML 文件的 DataContext 设置为您的 ViewModel:
<Window DataContext="{StaticResource ViewModel}">
现在通过绑定到 Command 类来响应您的事件:
<Button Click="{Binding Command}"></Button>
繁荣,没有代码隐藏。希望这会有所帮助。
另一种方式是:
最简单的方法是: