如何使用 Visual Studio“合并”XAML 文件及其代码隐藏

问题描述 投票:0回答:4
wpf visual-studio xaml code-behind
4个回答
41
投票

您需要编辑.csproj 文件。找到MyTemplate.cs的

<Compile>
元素,在其下添加一个
<DependentUpon>
元素:

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

请参阅此博客文章:使一个项目成为另一个项目的子项目


2
投票

这不是对您最初问题的回答,而是对这个问题的回答:

在那种情况下,请解释如何在不使用代码隐藏的情况下将事件处理程序添加到模板

您可以使用 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>

繁荣,没有代码隐藏。希望这会有所帮助。


2
投票

另一种方式是:

  • 添加/创建新的 XAML 文件/项目
  • 将旧的 .xaml 和 xaml.cs 内容复制并粘贴到新的等效文件
  • 删除单独的文件
  • 重命名新文件

0
投票

最简单的方法是:

  1. 从项目中排除未链接的文件
  2. 确保在解决方案资源管理器中启用“显示所有文件”
  3. 选择容器文件(本例中为.xaml 而不是xaml.cs),右键单击并包含在项目中。应该添加到项目中并修复链接。
© www.soinside.com 2019 - 2024. All rights reserved.