我有一个WPF应用程序,我使用Prism作为架构。
我有点习惯:
我有一个UserControl(向导),可以收到FrameworkElement
。此元素显示在向导usercontrol中,并带有ContentPresenter
。
基本上,使用此usercontrol的视图将包含以下代码:
<UserControl x:Class"My.Instance"
//skipping namespaces
mvvm:ViewModelLocator.AutoWireViewModel="True">
<Wizard>
<Wizard.ContentElement>
<TextBlock Text="{Binding MyInstanceProperty}"/>
</Wizard.ContentElement>
</Wizard>
</UserControl>
在“向导”UserControl中,我只有这样的事情:
<ContentControl Content="{Binding ContentElement}" Margin="10"/>
上下文是usercontrol背后的代码(在根Grid
上设置)。
在运行时,我遇到以下错误
System.Windows.Data错误:40:BindingExpression路径错误: 在'对象'''向导'上找不到'MyInstanceProperty'属性 (的HashCode = 29548405)”。 BindingExpression:路径= MyInstanceProperty; DataItem ='WizardViewModel'(HashCode = 29548405);目标元素是 'TextBlock'(Name =''); target属性是'Text'(类型'String')
所以看起来我的TextBlock在Wizard UserControl上设置了DataContext,但在“My.Instance”所有者上没有设置。
我想,这是因为我在ContentPresenter中托管它?
我该如何避免这种情况?
答案 0 :(得分:0)
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type UserControl}}, Path=DataContext.MyInstanceProperty}"/>
编辑&gt;&GT;&GT;&GT;&GT;
向导视图:
<ContentControl Content="{Binding ContentElement}" Margin="10"/>
向导视图模型:
ContentElement = new pageViewModel();
的App.xaml:
<DataTemplate DataType="{x:Type myViewModel:pageViewModel}">
<local:pageView/>
</DataTemplate>