Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement "View Model First" using Prism and Unity?

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.

like image 376
Kelson Ball Avatar asked Nov 08 '22 21:11

Kelson Ball


1 Answers

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>
like image 53
Kelson Ball Avatar answered Nov 14 '22 21:11

Kelson Ball