Bind DataContext and not set in code behind

662 views Asked by At

I have a WPF application and I use Prism and Unity. I have also two custom user controls:

  1. PlotViewControl
  2. PlotViewReport

The second uses the first control in a DataTemplate.

If I want to call:

regionManager.RequestNavigate("RightRegion", "PlotViewControl", parameters);

The DataContext for PlotViewControl must be set in PlotViewControl.xamls.cs like so:

this.DataContext =  new PlotViewModel();

If I want to use the above UserControl in PlotViewReport in the following manner, I must remove the line above.

<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>

So, which is the solution to be able to use the both scenarios.

1

There are 1 answers

0
Olaru Mircea On

Taking into consideration that you set the DataContext as {Binding} inside the ItemTemplate, this will point to the current ListView item. So, you have to use a RelativeSource binding to get to the DataContext of the ListView.

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