简体   繁体   English

如何从代码隐藏中访问XAML中已指定的DataContext?

[英]How to access a DataContext, that has been specified in XAML, from within code-behind?

I'm specifying my DataContext view model inside my XAML, as follows: 我在XAML中指定了DataContext视图模型,如下所示:

<Window.DataContext>
    <vm:SeasonDivisionViewModel />
</Window.DataContext>

If that SeasonDivisionViewModel class has a public property, is it possible to access this from within the code-behind? 如果SeasonDivisionViewModel类具有公共属性,是否可以从背后的代码中访问它?

I'm trying to learn and take one step at a time, and I'd like to avoid adding commands yet, and just populate data from within code-behind, for now. 我正在尝试一次学习并迈出一步,并且我想避免再添加命令,而现在只是从代码隐藏内部填充数据。

If you meant to access the DataContext after the view loads on the code behind you can simply use this. 如果您打算在视图加载后面的代码后访问DataContext,则可以简单地使用它。

var viewModel = (MyViewModel)DataContext;

Where MyViewModel is the data type of your data context. 其中MyViewModel是数据上下文的数据类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM