5
votes

Clarification I am working with an MVVM solution. I have a 1 to 1 mapping between ViewModels and Views. All solutions I have seen follow a view first approach where the View type is resolved by an IoC container and has a ViewModel as a dependency. I need to reverse that somehow.

Original post:

I am currently trying to refactor a simple database viewing application from Caliburn Micro to Prism (which I am very new to). The application currently utilizes a ViewModel-First approach and the ShellViewModel maintains a list of ViewModels that is bound to a TabControl. I can not find how to implement a similar approach in Prism. All solutions I have seen use a view first approach, but I have multiple states all mapping to one type of view and need to keep those states separate. Outline of application

Is there a way I can configure prism to automatically inject a view when a viewmodel is assigned to a region?

Thank you.

2
I think you're looking to use an implicit DataTemplate. That is simply a DataTemplate defined in XAML with a TargetType, but no Key. WPF will automatically use that DataTemplate to draw the specified object when it is encountered in the Visual Tree, such as when it tries to render a TabControl where ItemsSource is set to a collection of ViewModels. See here for an example if you want.Rachel

2 Answers

1
votes

Rachel pointed me to a solution in her comment to the original question. Instead of trying to implement special prism functionality and prism regions, I have gone with a more straight forward MVVM implementation using DataTemplates.

ViewModel outline:

public abstract class ContainerViewModel : BindableBase
{
    public ObservableCollection<ItemViewModel> Items { get; set; }
    public ItemViewModel ActiveItem { get; set; }

    protected virtual void Add(ItemViewModel item) { ... }
    protected virtual void Remove(ItemViewModel item) { ... }
    protected virtual void Activate(ItemViewModel item) { ... }
}

And XAML:

<TabControl Grid.Column="1" ItemsSource="{Binding Items}" SelectedItem="{Binding ActiveItem}">
                <TabControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Table.TableName}"    />
                    </DataTemplate>
                </TabControl.ItemTemplate>
                <TabControl.ContentTemplate>
                    <DataTemplate DataType="{x:Type viewModels:QueryViewModel}">
                        <local:QueryView />
                    </DataTemplate>
                </TabControl.ContentTemplate>
            </TabControl>
0
votes

Have a look at this code project article (ignoring the part about child containers): http://www.codeproject.com/Articles/640573/ViewModel-st-Child-Container-PRISM-Navigation