简体   繁体   English

viewmodel和view控件的执行顺序

[英]viewmodel and view control order of execution

I have a serious problem with the order of execution in MVVM: this code instaceiate the view (XAML): 我对MVVM中的执行顺序存在严重问题:此代码可实例化视图(XAML):

<local:ExecutionView x:Name="ExecutionView" DataContext="{Binding ExecutionViewNodel}"/>

ExecutionView has inner field of viewmodel ( _viewModel = DataContext as ExecutionViewModel; ). ExecutionView具有viewmodel的内部字段( _viewModel = DataContext as ExecutionViewModel; )。 In its CTOR it uses the viewmodel- _viewModel.DoSomthing(); 在其CTOR中,它使用viewmodel- _viewModel.DoSomthing();

problem is that it is null.. 问题是它为空。

I cant control the timing of the binding- i have read a bit and there ways of handling the issue with (Loaded event and datacontextchanged)- still i think it is a workaround and NOT the way it should be done. 我无法控制绑定的时间-我已经阅读了一些,并且有一些方法可以解决(加载事件和数据上下文已更改)的问题-我仍然认为这是一种解决方法,而不是应采取的方法。

i need a way to control the steps where i can write a function that will be called once after the DataContext is certain to be valid. 我需要一种方法来控制我可以编写在DataContext确定有效之后将被调用一次的函数的步骤。

BR, Mosh. BR,莫什。

Instead of using the DataContext in your constructor, when it isn't quite available yet, subscribe to the DataContextChanged event in the constructor, and when your even handler is called, grab the reference to the new DataContext and perform whatever operations you need. 尚未在构造函数中使用DataContext ,请使用构造函数中的DataContextChanged事件进行订阅,并在调用偶数处理程序时,获取对新DataContext的引用并执行所需的任何操作。

It's also possible to declare an event handler in your XAML, so the subscription to the event doesn't need to be in the constructor. 也可以在XAML中声明事件处理程序,因此事件的订阅不需要在构造函数中。

Here is a link to MSDN regarding that event. 这是有关该事件的MSDN链接

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

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