Sorry, I’m thrashing around a bit learning MVVM, WPF, and XAML simultaneously.
I have a problem that I created and I am completely confused with how this should be handled in MVVM.
What I have is a parent window that contains a user control that draws graphs. The graph drawing XAML used to be part of the parent window, but I moved it to a user control for organization as the parent window was very big.
In the parent windows XAML I have …..
<Window ....>
<Window.Resources>
<ViewModel:DropGraphViewModel x:Key="myViewModel"/>
</Window.Resources>
<!-- Set the data context to the view model. -->
<Window.DataContext>
<Binding Source="{StaticResource myViewModel}"/>
</Window.DataContext>
.....
</Window>
And then in the new user control XAML class I have a resource that is created that is a ‘generator’ class that serves up things that will be used by parts of the graph. It looks like this…
<UserControl ......
<!-- Graph resources -->
<Grid.Resources>
<!-- The binding here for ItemsSource represents the collection the graph will be bound to -->
<!-- THIS LINE DOESN'T WORK ANYMORE -->
<Graphs:LineChartGenerator x:Key="generator" ItemsSource="{Binding Source={StaticResource myViewModel}, Path=SampleData}" Width="500" Height="200"> -->
</Grid.Resources>
And then later on when I want to do some things like draw graph lines I used to reference the generator through binding.
<!-- Connect the points -->
<Polyline Points="{Binding Source={StaticResource generator}, Path=Points}" Stroke="Blue" />
What is now broken now that I am in am using a nested user control is that when I create the instance of the ‘generator’ class in the resources, I can’t pass in the binding that was ItemsSource=”{Binding Source={StaticResource myViewModel}, Path=SampleData}” because I no longer have access to the view model (myViewModel) that is in the static resource of the parent window! So I can’t set the binding during the creation time of the resource like I used to do.
What is the proper MVVM way to handle this type of pattern?
How do I inject the ItemsSource into my new user control so that it can pass it in when it creates the LineChartGenerator class instance?
DataContextis an inheritableDependencyPropertywhich means it trickles down the visual hierarchy.So in your case, your
Graphs:LineChartGeneratorhas to be hosted in yourUserControland not delcared in the Resource section. Once you do that it acquires its ownDataContextfrom the parentWindow, this way as @GazTheDestroyer, pointed out you only need a implicit bindingItemsSource="{Binding SampleData}"