首页 文章

如何将视图模型绑定到MVVMCROSS中的UserControl?

提问于
浏览
1

我正在使用优秀的Mvvmcross和Ninja Coder为Mvvmcross构建跨平台应用程序 . 对于我的Windows商店应用程序,我使用Ninja编码器创建了一个视图和一个视图模型 . 我还创建了一个UserControl,它将在视图中引用 . 因此,我还需要将相同的viewmodel绑定到User控件 . 我一直在尝试将用户控件的Data上下文设置为viewmodel的单例实例 . 我已经设置了用户控件的数据上下文,如下所示 .

public sealed partial class SearchResultsGridViewControl : UserControl
{
    private SearchresultsViewModel _viewModel;

    public SearchResultsGridViewControl()
    {
        this.InitializeComponent();

        _viewModel = Mvx.IocConstruct<SearchresultsViewModel>();

        this.DataContext = _viewModel;
    }
}

但是当我在主视图中引用此用户控件时,它会在XAML中抛出错误,指出“对象引用未设置为对象的实例 . 无法创建SearchResultsGridViewControl的实例” .

这是我的viewmodel:

public class SearchresultsViewModel : BaseViewModel
{
    private ISearchResultsService _searchResultsService;

    public SearchresultsViewModel(ISearchResultsService searchResultsService)
    {
        _searchResultsService = searchResultsService;
        var items = _searchResultsService.DisplaySearchResults();
        SchoolDetails = new ObservableCollection<School>(items);            
    }

    private ObservableCollection<School> _schoolDetails;

    public ObservableCollection<School> SchoolDetails
    {
        get { return _schoolDetails; }
        set
        {
            _schoolDetails = value;
            RaisePropertyChanged(() => SchoolDetails);
        }
    }

    public ICommand RefineCommand
    {
        get
        {
            refineCommand = refineCommand ?? new MvxCommand(FilterSearchResultsBasedOnRefine);
            return refineCommand;
        }
    }

    public void FilterSearchResultsBasedOnRefine()
    {           
        SchoolDetails = new ObservableCollection<School>(_searchResultsService.FilterSchoolsBasedOnRefine(MidDayMeals, PlayGround, DigitalClassroom, DayBoarding, TransportationFacility));
    }
}

我的usercontrol中的网格视图在第一次加载时会被填充 . 但是,当调用RefineCommand从主视图更新集合时,usercontrol中的网格视图不会更新 . 我猜测它是因为在设置用户控件的数据上下文以查看模型之前的错误 . 请让我知道可能出现的问题 . 几天以来,我一直在喋喋不休地谈论它 .

2 回答

  • 4

    我最近一直在使用MVVMCross和Windows Store . 不回头看我的代码,我很确定Datacontext将继承它的父级,除非被覆盖 .

    因此,只要您提供的MvxPage具有视图模型,您在XAML或代码隐藏中添加的任何用户控件都应共享相同的数据上下文 . 如果您正在考虑从用户控件执行一些MVVMCross数据绑定,您应该确保您的用户控件实现IMvxStoreView,并确保将ViewModel属性设置为DataContext的值 .

    希望有所帮助 .

    干杯,特里斯坦

  • 1

    我认为你的第一个问题"Object Reference not set to an instance of an object"只是一个设计时问题 - 因为你试图在设计时使用 Mvx. 设置viewmodel . 如果您希望通过使用设计时视图模型以及可能还使用其中一个设计时帮助程序(请参阅https://github.com/MvvmCross/MvvmCross/blob/v3.1/CrossCore/Cirrious.CrossCore.Wpf/Platform/MvxDesignTimeHelper.cs),则可以解决此问题 .


    我不知道你的第二个问题是什么"The grid view in my usercontrol is getting populated when it loads for the first time. But when RefineCommand is called to update the collection from the main view, the grid view in usercontrol is not getting updated" - 这听起来像是你的xaml或 FilterSearchResultsBasedOnRefine 返回的结果中的问题 . 从目前的详细程度来看,我可以_MtvmCross具体 - 它只是一个普通的Mvvm /数据绑定问题 .

相关问题