WPF数据上下文问题

本文关键字:问题 上下文 数据 WPF | 更新日期: 2023-09-27 18:13:04

我有一个WPF应用程序,我使用Prism作为架构。

我有一些自定义的东西:我有一个UserControl(一个向导),它可以接收FrameworkElement。此元素以ContentPresenter显示在向导用户控件中。

基本上,使用这个usercontrol的视图将有这样的代码:
<UserControl x:Class"My.Instance" 
  //skipping namespaces
  mvvm:ViewModelLocator.AutoWireViewModel="True">
    <Wizard>
        <Wizard.ContentElement>
            <TextBlock Text="{Binding MyInstanceProperty}"/>
        </Wizard.ContentElement>
    </Wizard>
</UserControl>

在"Wizard"UserControl中,我有这样的内容:

<ContentControl Content="{Binding ContentElement}" Margin="10"/>

上下文是用户控件背后的代码(设置在根Grid上)。

运行时,出现以下错误

System.Windows。数据错误:40:BindingExpression路径错误"MyInstanceProperty"属性在"object"上找不到(HashCode = 29548405)"。BindingExpression:路径= MyInstanceProperty;DataItem = ' WizardViewModel ' (HashCode = 29548405);目标元素是"TextBlock"(Name = ");目标属性为"Text"(类型为"String")

所以似乎我的TextBlock有它的DataContext设置在向导用户控制,但不是在"我的。实例"所有者。

我猜,这是因为我托管它在一个ContentPresenter?

我怎样才能避免这种情况?

WPF数据上下文问题

<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type UserControl}}, Path=DataContext.MyInstanceProperty}"/>

编辑>>>>>

向导视图:

<ContentControl Content="{Binding ContentElement}" Margin="10"/>

向导视图模型:

ContentElement = new pageViewModel();

App.xaml:

<DataTemplate DataType="{x:Type myViewModel:pageViewModel}">
    <local:pageView/>
</DataTemplate>