开发者

Sl 4, MVVM: When is the VM available for use by the View?

开发者 https://www.devze.com 2023-02-18 23:55 出处:网络
I have a View and set its DataContext to 开发者_JS百科the corresponding ViewModel.In the Loaded event handler in the View code-behind, I want to set some Properties on the VM.However, the View\'s Dat

I have a View and set its DataContext to 开发者_JS百科the corresponding ViewModel. In the Loaded event handler in the View code-behind, I want to set some Properties on the VM. However, the View's DataContext is null at that point.

In the xaml:

Loaded="UserControl_Loaded"
<UserControl.Resources>
    <viewModels:PageViewModel x:Key="vm" />
</UserControl.Resources>

In the Loaded handler, page.xaml.cs:

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
  PageViewModel pvm = this.DataContext as PageViewModel;
  System.Diagnostics.Debug.WriteLine("pvm is " + ((null == pvm) ? "null" : pvm.ToString()));
}

Am I doing something wrong, or is the VM not available, yet, when the View fires the Loaded event?

UPDATE: The real issue appears to be the VM is not getting hooked up to the View. In UserControl_Loaded, pvm is null.

Currently, I am setting the DataContext on the root element of the layout; does it need to be set on the UserControl? If so, how?

Thanks for any insight...


Replace

<UserControl.Resources>
    <viewModels:PageViewModel x:Key="vm" />
</UserControl.Resources>

by :

<UserControl.DataContext>
    <viewModels:PageViewModel />
</UserControl.DataContext>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号