我将 WPF 与 Model-View-ViewModel 模式一起使用。因此,我的文件后面的代码 (.xaml.cs) 都是空的,除了调用 InitializeComponent 的构造函数。因此,对于每个 .xaml 文件,我都有一个匹配的、无用的 .xaml.cs 文件。
我发誓我在某处读到过,如果文件后面的代码除了构造函数之外是空的,那么有一种方法可以完全从项目中删除文件。在网上搜索后,似乎这样做的适当方法是使用'x:Subclass'属性:
<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 文件中执行以下操作:
看起来很完美。实际上,如果您在构建中仍然有 .xaml.cs 文件,则由于缺少部分文件而不再编译 - 所以我认为这一定是正确的。但是,如果我从构建中删除多余的文件并运行,控件不会正确初始化(它是空白的)。我想这是因为 InitializeComponent() 没有被调用。我看到 InitializeComponent 不是虚拟的,所以基类似乎没有办法调用它(没有使用反射)。
我错过了什么吗?
谢谢!
埃里克
最佳答案
如果您关注 Josh Smith's MVVM article ,他将 DataTemplates 用于 Views 而不是用户控件。如果您将 DataTemplates 放入 ResourceDictionaries,它们根本没有代码隐藏。如果您不使用用户控件的代码隐藏,这是否意味着您可以使用 DataTemplate 方法?如果您这样做,WPF 将负责将您的 View 绑定(bind)到您的 ViewModel。
关于wpf - 没有 .xaml.cs 代码的 XAML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1841646/