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

gk7wooem  于 2023-04-18  发布在  其他
关注(0)|答案(4)|浏览(177)

我在名为“MyTemplate.xaml”的XAML文件中定义了一个模板。此模板使用名为“MyTemplate.cs”的代码隐藏文件。

Mytemplate.xaml

<ResourceDictionary x:Class="Project.Templates.MyTemplate">
    <DataTemplate ... />
</ResourceDictionary>

我的模板.cs

namespace Project.Templates
{
    public partial class MyTemplate : ResourceDictionary
    {
        ...
    }
}

在Visual Studio解决方案资源管理器中,这两个文件是并排的。我想做的是将这两个文件放在一起,就像控件及其代码隐藏一样。
我有什么:

我想要的是:

最好的方法是什么?谢谢。

pxiryf3j

pxiryf3j1#

您需要编辑.csproj文件。找到MyTemplate.cs的<Compile>元素,并在其下添加<DependentUpon>元素:

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

查看此博客文章:make a project item a child item of another

ctrmrzij

ctrmrzij2#

这不是对你最初问题的回答,而是这个:
在这种情况下,请解释如何在不使用代码隐藏的情况下向模板添加事件处理程序
您可以使用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; }
    }
}

将ViewModel作为静态资源添加到App.xaml文件中:

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

将XAML文件的DataContext设置为ViewModel:

<Window DataContext="{StaticResource ViewModel}">

现在通过绑定到Command类来响应事件:

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

嘣,没有代码隐藏。希望这能帮上忙。

vlf7wbxs

vlf7wbxs3#

另一种方法是:

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

pxy2qtax4#

最简单的方法是:
1.从项目中排除未链接的文件
1.确保在解决方案资源管理器中启用了“显示所有文件
1.选择容器文件(本例中为.xaml而非xaml.cs),右键单击并包含在项目中。应添加到项目中并修复链接。

相关问题