【问题标题】:How to start using MvvmLight on a .net core 3 WPF app?如何在 .net core 3 WPF 应用程序上开始使用 MvvmLight?
【发布时间】:2019-11-07 10:36:01
【问题描述】:

对于一个新项目,我想尝试新的 .net core 3.0 WPF 项目,我想将它与 MvvmLight 结合使用。但是,在 .net 核心中并与 Visual Studio Code 结合使用时,您不会获得任何脚手架或默认项目。然后是如何让它工作的奥秘......

我知道我需要在 app.xaml.cs、mainwindow.xaml 和 mainwindow.xaml.cs 中做一些事情。以及创建一些 ViewModelLocator 服务。但是 MvvmLight 的文档在这方面有点空。

我在 SO (MvvmLightLibsStd10 and UWP) 上找到了以下问题,但在我的情况下它并不完整,我也不确定我应该使用普通包还是特殊的 std10 版本。

2019-06-26 更新 我使用 MvvmLightLibsStd10 版本 5.4.1.1 使用以下代码。

App.xaml

    <Application.Resources>
        <ResourceDictionary>
            <vm:ViewModelLocator x:Key="Locator" xmlns:vm="clr-namespace:$AssemblyName$.ViewModel" />
        </ResourceDictionary>
    </Application.Resources>

MainWindow.xaml

        DataContext="{Binding ValidatorListViewModel, Source={StaticResource Locator}}">

ViewModelLocator.cs

using GalaSoft.MvvmLight.Ioc;

namespace $AssemblyName$.ViewModel
{
    public class ViewModelLocator
    {
        public ViewModelLocator()
        {
            SimpleIoc.Default.Register<ValidatorListViewModel>();
        }

        public ValidatorListViewModel ValidatorListViewModel => SimpleIoc.Default.GetInstance<ValidatorListViewModel>();
    }
}

【问题讨论】:

    标签: wpf data-binding mvvm-light .net-core-3.0


    【解决方案1】:

    自从您提出这个问题后的 1.5 年里,发生了很多事情。 Microsoft 现在支持替换 MVVMLight。您听说过 Microsoft.Toolkit.MVVM 吗?请参见: https://github.com/windows-toolkit/MVVM-Samples 它应该与 .NET Core 更兼容。哎呀,我忘了它现在只是 .NET(适用于 Rev5 及以上版本)

    【讨论】:

      【解决方案2】:

      在我的情况下不完整”到底是什么意思?您在构建项目时是否遇到任何错误?

      我也在我的项目中使用 MvvmLight。 举个例子:

      在 App.xaml 中

      <ResourceDictionary>
                      <vm:ViewModelLocator x:Key="Locator"
                                           d:IsDataSource="True"
                                           xmlns:vm="clr-namespace:$AssemblyName$.ViewModel" />
      </ResourceDictionary>
      

      在 MainWindow.xaml 中

      DataContext="{Binding Main, Source={StaticResource Locator}}"
      

      在 ViewModelLocator.cs 中

      public ViewModelLocator()
      {
         ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
         SimpleIoc.Default.Register<MainViewModel>();
      }
      
      public MainViewModel Main
      {
           get
           {
               return ServiceLocator.Current.GetInstance<MainViewModel>();
           }
      }
      

      这应该可以解决问题...但是如上所述,如果您遇到任何错误,知道会很有趣。

      【讨论】:

      • 不,我不知道该放在哪里,因为 .net core 3 和 VS Code 中的默认值为 0 脚手架,并且缺少文档,因此您必须通过魔术找到它。 ..我今天下午晚些时候有一个工作版本。但是您拥有的 ViewModelLocator 看起来更干净。当我回到代码时,我会分享一些内容!
      • 在我的版本中,ServiceLocator 类不再可用,这也是由于 .net core 3 支持的版本。结合您的反馈和我已经找到的问题,确保我明白了去工作。干杯!谢谢!
      • 很高兴我能帮上忙。您能否将我的建议标记为答案,以便其他人也可以遵循此建议。谢谢!
      猜你喜欢
      • 2011-08-27
      • 2020-12-02
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      相关资源
      最近更新 更多