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类中。