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?
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With