XAML没有文件后面的.xaml.cs代码 [英] XAML without the .xaml.cs code behind files

查看:247
本文介绍了XAML没有文件后面的.xaml.cs代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将WPF与Model-View-ViewModel模式一起使用。因此,除了调用InitializeComponent的构造函数之外,文件(.xaml.cs)后面的代码都为空。因此,对于每个.xaml文件,我都有一个匹配的,无用的.xaml.cs文件。

I'm using WPF with the Model-View-ViewModel pattern. Thus, my code behind files (.xaml.cs) are all empty, except for the constructor with a call to InitializeComponent. Thus, for every .xaml file I have a matching, useless, .xaml.cs file.

我发誓我读过某个地方,如果文件后面的代码为空,则除了构造函数,有一种方法可以从项目中完全删除文件。搜索完网络后,看来执行此操作的适当方法是使用'x:Subclass'属性:

I swear I read somewhere that if the code behind file is empty except for the constructor, there is a way to delete the file from the project altogether. After searching the net, it seems that the appropriate way to do this is to use the 'x:Subclass' attribute:

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
    x:Class="MyNamespace.MyClass"
    x:Subclass="UserControl"
    d:DesignWidth="700" d:DesignHeight="500">

此操作在生成的.g.cs文件中执行以下操作:

This does the following in the generated .g.cs file:


  1. 删除MyClass上的 partial类修饰符。

  2. 将 UserControl类添加到其子类列表中。

似乎很完美。确实,如果您仍在构建中.xaml.cs文件,由于缺少部分内容,该文件将不再编译-因此,我认为这一定是正确的。但是,如果我从构建中删除了多余的文件并运行,则该控件将无法正确初始化(它为空)。我想这是因为未调用InitializeComponent()。我看到InitializeComponent不是虚拟的,因此基类似乎无法调用它(缺少反射)。

Seems perfect. Indeed, if you still have the .xaml.cs file in the build, it no longer compiles because of the missing partial--so I'm thinking this must be correct. However, if I remove the superfluous file from the build and run, the control does not get initialized correctly (it is blank). This is, I presume, because InitializeComponent() is not getting called. I see InitializeComponent is not virtual, so it seems there would be no way for the base class to call it (short of using reflection).

我错过了什么吗?

谢谢!

Eric

推荐答案

如果您遵循乔什·史密斯的MVVM文章,他将DataTemplates用于视图而不是用户控件。如果将DataTemplates放入ResourceDictionaries,则它们根本没有代码隐藏。如果您不使用用户控件的代码,这是否意味着您可以使用DataTemplate方法?如果这样做,WPF将为您将View绑定到ViewModel。

If you follow Josh Smith's MVVM article, he uses DataTemplates for Views rather than user controls. If you put your DataTemplates into ResourceDictionaries, they don't have a code-behind at all. If you're not using the code-behind of your user control, doesn't that mean you could use a DataTemplate approach? If you do that, WPF will take care of binding your View to your ViewModel for you.

这篇关于XAML没有文件后面的.xaml.cs代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆