【问题标题】:"Method not found" error in XAML designerXAML 设计器中的“找不到方法”错误
【发布时间】:2015-02-21 03:11:05
【问题描述】:

当我在 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 属性下放了一条蓝色的弯线,我在错误列表中看到:

错误 7 找不到方法:'无效 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= 使这个测试视图模型成为实际的数据上下文。在这种情况下,我打开应用程序并确认,在运行时,一切都按预期工作:TestData.ELabelViewModel 被调用,getter 函数内部的代码运行,并且它使用了这个视图模型。只是设计者未能运行代码。

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

稍后编辑

我尝试将这个 TestData 类移动到 ELabel.Manager.ViewModels 程序集(构造函数所在的程序集)。果然,现在可以正常工作了,在编辑器中查看控件时可以看到测试数据。好奇。

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

【问题讨论】:

  • 也许这只是程序集引用的问题,您的静态类根本不知道,因此可能导致 void 返回。
  • 让我猜——在设计器中给出了一个错误,但它编译并运行良好?设计师一直在做这种废话。忽略它。希望它在 15 年会更加可靠。
  • @Will,现在是 15 岁,问题还在继续 :)
  • 我在使用来自 dll 库的静态方法时遇到了类似的问题。

标签: c# wpf xaml mvvm


【解决方案1】:

我的所有视图模型类都是这样实现的:

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 2016-05-08
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    相关资源
    最近更新 更多