0

I'm writing a small WPF app with only 3 pages (for now). I'm using DataTemplate and ContentControl in the main window to display and switch between my pages. (See code sample below). It's working but I have a few concerns:

  1. The DataTemplate use parameterless constructor only. If I add one then It can't find the constructor.

  2. The 'registration' is done in the xaml and I cannot use Dependency Injection to link Views with ViewModels.

Questions:

Is there a way to change that without using third party tool?

If the only good option is to use a tool, which ones should I consider?

<Window.Resources>
    <DataTemplate DataType="{x:Type pageViewModels:HomePageViewModel}">
        <pageViews:HomePageView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type pageViewModels:GamePageViewModel}">
        <pageViews:GamePageView />
    </DataTemplate>
</Window.Resources>

<DockPanel>
    <Border DockPanel.Dock="Left" BorderBrush="Black" BorderThickness="0,0,1,0">
        <ItemsControl ItemsSource="{Binding PageViewModels}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Content="{Binding Name}"
                            Command="{Binding DataContext.ChangePageCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                            CommandParameter="{Binding }"
                            Margin="2,5"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Border>

Edit To clarify, I want to inject a class in the constructor of my viewsModels, but if I do that then the navigation within my application is broken because the dataTemplate is looking for the parameterless constructor.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • Unclear question. What u r trying to achieve ? – AnjumSKhan Oct 09 '16 at 08:34
  • I'm trying to inject another class in the constructors of my viewModels, but I cant' because the declareation in the xaml is using the parameterless constructor. I want to find a way to fix the points 1) and 2), that I list above. – Cedric Royer-Bertrand Oct 10 '16 at 12:31
  • creation of viewmodels should be handled by other viewmodels (or your app initializer when entering the application). all your view should be doing is declaring how it is rendered. so far this looks good. show more of your VM code - you're probably just slightly off the pattern since this seems to be an issue for you right now :) – Dbl Oct 10 '16 at 12:43

1 Answers1

0

It looks like my problem has been very well explained in this post.

In short, I need to implement a ViewModelLocator pattern in order to fix all my concerns.

Community
  • 1
  • 1