从 ViewModel 中提取数据

我有一个视图模型:


public class CreateRepositoryViewModel : BaseViewModel

{

    private Repository _repository;

    public Repository Repository

    {

        get => _repository;

        set

        {

            _repository = value;

            OnPropertyChanged();

        }

    }

}

(BaseViewModel实现IPropertyChanged接口以简化)


然后我将视图模型绑定到我的页面,如下所示:


DataContext = new CreateRepositoryViewModel();

然后我有多个绑定到 ViewModel 的表单字段:


<TextBox Text="{Binding Path=Repository.LicenceTemplate}" />

<CheckBox IsChecked="{Binding Path=Repository.HasIssues}" VerticalAlignment="Center"/>

在页面内的按钮单击事件模型上,我尝试提取数据,如下所示:


var model = (CreateRepositoryViewModel) DataContext;

但是,数据上下文中的 Repository 属性返回 null。如何获取xaml页面后面的.cs文件中的这些数据?


慕侠2389804
浏览 79回答 1
1回答

跃然一笑

ViewModel 中的存储库属性需要实例化。DataContext = new CreateRepositoryViewModel { Repository = new Models.Repository() };或者,为属性的支持字段分配一个非空初始值。public class CreateRepositoryViewModel : BaseViewModel{&nbsp; &nbsp; private Repository _repository = new Models.Repository();&nbsp; &nbsp; ...}那么这就足够了:DataContext = new CreateRepositoryViewModel();
打开App,查看更多内容
随时随地看视频慕课网APP