【问题标题】:CommunityToolkit.MVVM The namespace 'namespace' already contains a definition for 'type'CommunityToolkit.MVVM 命名空间“namespace”已经包含“type”的定义
【发布时间】:2022-07-18 05:01:57
【问题描述】:

我想在 .NET MAUI 中使用 MVVM,我从 CommunityToolkit.MVVM 开始。

我创建了一个视图模型并得到以下错误:

The namespace 'MyApp.ViewModels' already contains a definition for 'ProfilePopupViewModel '

这是视图模型:

public class ProfilePopupViewModel : ObservableRecipient
    {
        private Profile Profile;

        [ObservableProperty]
        private string id;
        [ObservableProperty]
        private string name;
        [ObservableProperty]
        private DateOnly birthDate;
        [ObservableProperty]
        private int work;
    }

谢谢!

马库斯

【问题讨论】:

    标签: c# mvvm maui


    【解决方案1】:

    你的类型需要是部分的:

    public partial class ProfilePopupViewModel : ObservableRecipient
    {
        [ObservableProperty]
        private string id;
        // ...
    }
    

    MVVM 工具包包含一个Source Generator。这通过获取您添加的那些 ObservableProperty 属性并生成添加到编译中的 C# 代码来工作。

    对于您的课程,它将生成另一个partial class,其中包含与您的[ObservableProperty] 字段对应的属性。比如:

    partial class ProfilePopupViewModel
    {
        public string Id
        {
            get => id;
            set
            {
                if (id != value)
                {
                    id = value;
                    OnPropertyChanged("Id");
                }
            }
        }
    
        // ...
    }
    

    为了编译,您的ProfilePopupViewModel 还需要标记为partial

    【讨论】:

      【解决方案2】:

      啊……当然——会阅读的人优势明显

      谢谢!

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      • 我认为您打算将此作为评论发布,无论是对我的回答还是对您的问题。但是,您将其发布为问题的答案,并且审核过程已将其标记。请使用相关位置下的“添加评论”链接添加评论
      【解决方案3】:

      这似乎是 .NET 6.0.302 和源代码生成器(如 Toolkit.MVVM 中的 on)的一个已知错误(请参阅 https://github.com/dotnet/wpf/issues/6792

      【讨论】:

        猜你喜欢
        • 2022-08-13
        • 2016-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多