如何编写与 ViewModel class 绑定的嵌套 class?

How to write a nested class that binds with a ViewModel class?

我的页面应该有一些视图模型。我决定尝试 Nested classes。我在我的项目中使用 MVVM Light。

我已经编写了 VM,它继承自 ViewModelBase 和嵌套的 class。

我用了微软文档的例子(嵌套例子):

    public class UserMainViewModel : ViewModelBase
    {
        public UserMainViewModel()
        {

        }

        private Page _mainContent;

        public Page MainContent
        {
            get => _mainContent;
            private set => Set(ref _mainContent, value);
        }   

        public UserVM UserManager
        {
            get
            {
                return new UserVM(new UserMainViewModel());
            }
        }

        public class UserVM
        {
            private UserMainViewModel _viewModel;

            public UserVM(UserMainViewModel viewModel)
            {
                _viewModel = viewModel;
            }

            private RelayCommand _getInfoPageCommand;
            public RelayCommand GetInfoPageCommand
            {
                get
                {
                    return _getInfoPageCommand
                        ?? (_getInfoPageCommand = new RelayCommand(() =>
                        {
                            _viewModel.MainContent = new GetUserInfo();
                        }));
                }
            }
        }
    }

我的 ViewLocator:

     public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
            SimpleIoc.Default.Register<UserMainViewModel>();
        }

    public UserMainViewModel UserMainContext => ServiceLocator.Current.GetInstance<UserMainViewModel>();

查看上下文

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

例如元素视图

    <Button Content="Profile" Command="{Binding UserManager.GetInfoPageCommand}"/>

但是当我点击按钮时它不起作用。没有任何反应。

我使用嵌套 classes 的想法是否正确?谁能告诉我为什么它不起作用?

您的 UserVM 也需要继承自 ViewModelBase

public class UserVM : ViewModelBase

简而言之,ViewModelBase 已内置所有 Notification 管道,没有它,RelayCommand 无法知道它已被 notified/called.

您应该创建一个 UserVM 并将 UserMainViewModel 的当前实例传递给它,而不是每次调用 属性 时都创建一个新实例:

private UserVM _userVm;
public UserVM UserManager
{
    get
    {
        if (_userVm == null)
            _userVm = new UserVM(this);
        return _userVm;
    }
}