MVVM - Binding Expression errors when createing a View in XAML with a ViewModel DataTemplate

て烟熏妆下的殇ゞ 提交于 2019-12-11 12:39:43

问题


This is a WPF application.

Background:

I essentially have a Wizard application. The Wizard is initialized by providing a list of ViewModels. These ViewModels will create the appropriate view based on some DataTemplate in my XAML.

When clicking next or previous in the Wizard, the appropriate ViewModel will be set and the view will be loaded based on the DataTemplate.

This works fine.

Problem:

When I'm in a transitory state...meaning the new viewModel is being loaded, it appears there is a brief amount of time where the previous VIEW is still being referenced. Because of this, I get a bunch of BindingExpression errors where it says it cannot find a bunch of bindings which actually existed on the PREVIOUS viewModel.

SUMMARY: I'm loading a new view based on a DataTemplate. When that view is initially loaded, it appears to be out of sync with the actual viewModel. As such I get a bunch of binding expression errors.

Two questions:

  1. Any thoughts on how to fix this?
  2. Any dangers to having these BindingExpression errors?

    <wiz:WizardContent.Resources>
        <!--DataTemplates for defining views for this Wizard-->
        <DataTemplate DataType="{x:Type viewModel:Step1ViewModel}">
            <view:Step1 DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}, Path=DataContext.CurrentPageVM}"/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type viewModel:Step2ViewModel}">
            <view:Step2 DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}, Path=DataContext.CurrentPageVM}"/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type viewModel:Step3ViewModel}">
            <view:Step3 DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}, Path=DataContext.CurrentPageVM}"/>
        </DataTemplate>
    </wiz:WizardContent.Resources>
    <ContentControl Content="{Binding Path=CurrentPageVM}"/>
    


回答1:


BindingExpression errors aren't dangerous, as far as I know of, it just slows your app a little.

Concerning your code, I'm not sure you need to define DataContext in each view, since it automatically takes the DataContext detected by the DataType.



来源:https://stackoverflow.com/questions/16221021/mvvm-binding-expression-errors-when-createing-a-view-in-xaml-with-a-viewmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!