I'm new with WPF and I was just doing a simple menu using MVVM with bindings and commands but I think I'm doing something wrong. I just want to change all the Window Content importing a new UserControl
I defined, everytime I press a Menu Button. That means I want to disappear the menu and show a new content (the UserControls I mentioned before).
Well I have the main window (ControlPanel):
<Window x:Class="OfficeMenu.Views.Menu.ControlPanel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Control Panel" Height="800" Width="800">
<Grid>
<ContentControl Content="{Binding contentWindow}"/>
</Grid>
</Window>
This one of the UserControls that provides a Menu of buttons to the Main Window when I run the project:
<UserControl x:Class="OfficeMenu.Views.ButtonsMenu"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<!-- One style for each *type* of control on the window -->
<Style TargetType="Button">
<Setter Property="Margin" Value="5"/>
</Style>
</UserControl.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<Button Command="{Binding OpenUsersCommand}">BUTTON 1</Button>
<Button Grid.Column="1">BUTTON 2</Button>
<Button Grid.Column="1" Grid.Row="2" >BUTTON 3</Button>
<Button Grid.Row="1">BUTTON 4</Button>
</Grid>
</UserControl>
This is the ViewModel Im using for it:
class MenuViewModel : ViewModelBase
{
RandomModel _model; <!-- It does nothing important -->
private UserControl _content;
public ICommand OpenUsersCommand { get; private set; }
public UserControl Content
{
get { return _content; }
set {
_content = value;
NotifyPropertyChanged("contentWindow");
}
}
public MenuViewModel(RandomModel model )
{
this._model= model;
OpenUsersCommand = new RelayCommand(OpenUsers,null);
}
private void OpenUsers()
{
Content = new UsersPanel(); //This is the UserControl we need to load dinamically
}
}
In App.xaml.cs we load the main window:
public partial class App : Application
{
private void OnStartup(object sender, StartupEventArgs e)
{
ControlPanel view = new ControlPanel();
view.ShowDialog();
}
}
Now, the controlPanel.xaml.cs:
public ControlPanel()
{
InitializeComponent();
ModelRandom model = new ModelRandom(); <!-- It does nothing yet -->
MenuViewModel viewmodel = new MenuViewModel(model);
Content = new BottonsMenu(); <!-- We load a default UserControl when we run the program -->
this.DataContext = viewmodel;
}
}
Thank you very much.