Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - MVVM - Conditionally include user controls to view

In WPF my MVVM application I need to create an account search view with 2 options simple search by account # or Advanced search (by name, email, etc.)

In my AccountSearchViewModel I have a bool property IsAdvancedMode.

Also I have created 2 UserControls for each mode: SimpleSearchView and AdvancedSearchView

Now I need to show either one based on IsAdvancedMode property.

What is the best way to do it?

Also as a general solution what if I have SearchMode property that is enum. How whould you switch between multiple controls in that case?

like image 650
Michael D. Avatar asked Dec 28 '22 16:12

Michael D.


2 Answers

I think you need to use Data Templating, to do that you need to create three classes:

     public class Search
        {
            //Your Code
        }

        public class AdvanceSearch : Search
        {
           //Your Code
        }

        public class SimpleSearch : Search
        {
          //Your Code
        }

and then create Data Template base on Classes:

<DataTemplate DataType="{x:Type local:AdvanceSearch }">
  <StackPanel>
    <TextBlock Text="{Binding Path=Name}" />
    <TextBlock Text="{Binding Path=Email}"/>    
  </StackPanel>
</DataTemplate>

<DataTemplate DataType="{x:Type local:SimpleSearch }">
  <StackPanel>
    <TextBlock Text="{Binding Path=Name}" />    
  </StackPanel>
</DataTemplate>
like image 90
Behnam Avatar answered Dec 30 '22 05:12

Behnam


I would use a DataTrigger to swap out the ContentTemplate of a ContentControl as needed. I wrote an article about switching Views in MVVM here if you're interested (examples included)

Here's some quick test code demonstrating it:

<Window.Resources>
    <DataTemplate x:Key="TemplateA" >
        <TextBlock Text="I'm Template A" />
    </DataTemplate>

    <DataTemplate x:Key="TemplateB" >
        <TextBlock Text="I'm Template B" />
    </DataTemplate>
</Window.Resources>

<StackPanel>
    <ToggleButton x:Name="Test" Content="Test" />

    <ContentControl>
        <ContentControl.Style>
            <Style TargetType="{x:Type ContentControl}">
                <Setter Property="ContentTemplate" Value="{StaticResource TemplateA}" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=Test, Path=IsChecked}" Value="True">
                        <Setter Property="ContentTemplate" Value="{StaticResource TemplateB}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ContentControl.Style>
    </ContentControl>
</StackPanel>
like image 27
Rachel Avatar answered Dec 30 '22 06:12

Rachel