c# - XAML 设计器中的 "Method not found"错误

标签 c# wpf xaml mvvm

当我在 Visual Studio 的 WPF 设计器中查看数据时,我希望我的用户控件显示数据。

ViewModel 没有默认构造函数,因此我编写了自己的静态 TestData 类来构造模型及其所有依赖项。

public static class TestData
{
    public static ELabelViewModel ELabelViewModel
    {
        get
        {
            return new ELabelViewModel
            (
                new ControlPanelGridLine(TestData.ELabel),
                new SerialPortFactoryImpl(),
                new Repository(),
                new PriceLabelGenerator(TestData.IPriceLabelViewModelFactory)
            );
        }
    }

    // Other static getter methods

这一切编译没有问题。但是,当我将其添加到 XAML 中时,问题就开始了:

   d:DataContext="{x:Static local:TestData.ELabelViewModel}"

XAML 编辑器在我的 d:DataContext 属性下放置了一条蓝色卷线,在错误列表中我看到:

Error 7 Method not found: 'Void ELabel.Manager.ViewModels.ELabelViewModel..ctor(ELabel.Manager.ViewModels.ControlPanelGridLine, ELabel.Control.ISerialPortFactory, ELabel.Data.IRepository, ELabel.ImageGeneration.IPriceLabelGenerator)'.

我对此的解释是,它正在寻找 TestData 类,同时也在寻找 TestData.ELabelViewModel 属性。它只是无法解析在 getter 内部调用的构造函数。

为什么找不到 ELabelViewModel 构造函数?为了确认我的代码没有问题,我使用 DataContext= 而不是 d:DataContext= 使这个测试 View 模型成为实际的数据上下文。在这种情况下,我打开了应用程序并确认在运行时一切都按预期工作:调用了 TestData.ELabelViewModel,运行了 getter 函数中的代码,并且它使用了这个 View 模型。只是设计人员未能运行代码。

ELabelViewModel 类位于名为 ELabel.Manager.ViewModels 的单独程序集中。编辑器是否未能完全加载此程序集?

稍后编辑

我尝试将此 TestData 类移动到 ELabel.Manager.ViewModels 程序集(构造函数所在的同一程序集)。果然,现在可以正常使用了,我在编辑器里查看控件的时候可以看到测试数据。好奇。

我仔细检查了 ELabelViewModel 类和构造函数是否是公共(public)的(当然是公共(public)的,否则我永远无法构建应用程序)。

最佳答案

我像这样实现我所有的 View 模型类:

<UserControl x:Class="MyApp.Views.MainView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:vm="clr-namespace:MyApp.ViewModel"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" Height="607" Width="616">

    <UserControl.DataContext>
        <vm:TestData/>
    </UserControl.DataContext>

关于c# - XAML 设计器中的 "Method not found"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28641652/

相关文章:

wpf - LINQ to Entities 异常(ElementAtOrDefault 和 CompareObjectEqual)

c# - 多级时如何将 View 绑定(bind)到 VM 包装器而不是直接绑定(bind)到模型

c# - 如果对象是特定类,则检查数据触发器

c# - 使用变量访问 WPF 元素

c# - "Sequence contains no elements"错误

c# - 按下 Button1 的边缘时,MessageBox 有时无法打开

C# - Nhibernate 问题

c# - log4net:在代码中使用 PatternString,而不是在配置文件中

c# - 如何使用 C# 在 URL 中检索 # 之后的值

c# - 不带参数的 DbContext ExecuteSQLCommand