Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF MVVM switch usercontrols

I am new to MVVM and WPF but I know what's going on in MVVM. I have a problem with switching between user controls in mainwindow. In my app I have: MainWindow.xaml with log and 2 links: Show all and Create new. Of course I have ViewModel for it. I have 2 more UserControls: ShowAll and Create with ViewModels and all logic in it (adding data etc). How can I show create form when I click link Create new or show all when I click ShowAll?

In windowForms I just hide UC, buto here is no code behind :)

My MainWindow.xaml:

<Window x:Class="Test.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="300">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding Name}"/>
            <Button Content="Change" Command="{Binding ChangeCommand}"/>
        </StackPanel>
    </Grid>
</Window>

My MainWindowViewModel:

class MainWindowViewModel : BaseViewModel
{
    private Person _person;
    private BaseCommand _changeCommand;

    public MainWindowViewModel()
    {
        _person = new Person();
    }

    public string Name
    {
        get
        {
            return _person.Name;
        }
        set
        {
            if (_person.Name != value)
                _person.Name = value;
            OnPropertyChanged(() => Name);
        }
    }

    public ICommand ChangeCommand
    {
        get
        {
            if (_changeCommand == null)
                _changeCommand = new BaseCommand(() => change());
            return _changeCommand;
        }
    }

    private void change()
    {
        _person = new Person();
        Name = _person.Imie;
    }
}

In Create and ShowAll there is no code. In xaml only a label, VM is empty. Just for test.

Thank's for help!

like image 339
Chris Avatar asked Oct 21 '13 17:10

Chris


1 Answers

You can use a ContentControl to display a specific DataTemplate based on the type of ViewModel that is bound to the ContentControl.

http://www.japf.fr/2009/03/thinking-with-mvvm-data-templates-contentcontrol/

The command that is bound to the ShowAll button can simply change a property on your main ViewModel which is what is bound to your content control.

like image 160
Slugart Avatar answered Oct 25 '22 04:10

Slugart