Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 绑定DataContext,而不是在代码隐藏中设置_C#_Wpf_Xaml_Datacontext - Fatal编程技术网

C# 绑定DataContext,而不是在代码隐藏中设置

C# 绑定DataContext,而不是在代码隐藏中设置,c#,wpf,xaml,datacontext,C#,Wpf,Xaml,Datacontext,我有一个WPF应用程序,我使用Prism和Unity。我还有两个自定义用户控件: PlotViewControl PlotViewReport 第二个使用数据模板中的第一个控件 如果我想打电话: regionManager.RequestNavigate("RightRegion", "PlotViewControl", parameters); 必须在PlotViewControl.xamls.cs中设置PlotViewControl的数据上下文,如下所示: this.DataContext

我有一个
WPF
应用程序,我使用
Prism
Unity
。我还有两个自定义用户控件:

  • PlotViewControl
  • PlotViewReport
  • 第二个使用
    数据模板中的第一个控件

    如果我想打电话:

    regionManager.RequestNavigate("RightRegion", "PlotViewControl", parameters);
    
    必须在
    PlotViewControl.xamls.cs
    中设置
    PlotViewControl
    的数据上下文,如下所示:

    this.DataContext =  new PlotViewModel();
    
    如果要以以下方式使用
    PlotViewReport
    中的上述
    UserControl
    ,则必须删除上面的行

    <ListView Name="PlotLista" SelectedIndex="{Binding SelectedValue}" 
              ItemsSource="{Binding PlotReportModelList}" 
              HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <ListView.ItemTemplate>
            <DataTemplate>
                <!--<ItemsControl ItemsSource="{Binding }">-->
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding}"/>
                    <pv:PlotViewControl DataContext="{Binding }"  />
                </StackPanel>
                <!--</ItemsControl>-->
            </DataTemplate>
        </ListView.ItemTemplate>
    
    
    

    因此,这是能够使用这两种方案的解决方案。

    考虑到您在ItemTemplate中将DataContext设置为{Binding},这将指向当前的ListView项。因此,必须使用RelativeSource绑定才能访问ListView的DataContext

    Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.ViewModel}"
    

    我想你在窗口中有一个列表视图。哪一个是数据上下文?PlotReportModelList位于哪里?在PlotViewReport的ViewModel类中。