当我在构造函数中进行设置时,MainMenuView中的ContentControl将更新,但此后不会更新。我试图让它更改按钮单击。该命令似乎正在运行,并更改了CurrentPageViewModel的值。我正在遵循此代码示例来更改视图https://rachel53461.wordpress.com/2011/12/18/navigation-with-mvvm-2/。
MainMenuViewModel:
public MainMenuViewModel()
{
SelectViewCommand = new RelayCommand<IPageViewModel>(s => ChangeViewModel(s));
PageViewModels.Add(new ClockViewModel());
CurrentPageViewModel = PageViewModels[1];
}
private List<IPageViewModel> pageViewModels;
public List<IPageViewModel> PageViewModels
{
get
{
if (pageViewModels == null)
pageViewModels = new List<IPageViewModel>();
return pageViewModels;
}
}
private IPageViewModel currentPageViewModel;
public IPageViewModel CurrentPageViewModel
{
get { return currentPageViewModel; }
set { currentPageViewModel = value; OnPropertyChanged("currentPageViewModel"); }
}
public RelayCommand<IPageViewModel> SelectViewCommand { get; private set; }
private void ChangeViewModel(IPageViewModel viewModel)
{
if (!PageViewModels.Contains(viewModel))
PageViewModels.Add(viewModel);
CurrentPageViewModel = PageViewModels
.FirstOrDefault(vm => vm == viewModel);
}
private void OnPropertyChanged(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
throw new ArgumentNullException("propertyName");
var changed = PropertyChanged;
if (changed != null)
{
changed(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
MainMenuView:
<Window x:Class="TextApp.View.MainMenuView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TextApp.View"
xmlns:local1="clr-namespace:TextApp.ViewModel"
mc:Ignorable="d"
Title="MainMenuView" Height="450" Width="800">
<Window.Resources>
<DataTemplate DataType="{x:Type local1:ClockViewModel}">
<local:ClockView/>
</DataTemplate>
<DataTemplate DataType="{x:Type local1:IPageViewModel}">
<local:IPageView/>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.3*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<ItemsControl ItemsSource="{Binding PageViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}"
Command="{Binding DataContext.SelectViewCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding}"
Margin="2,5"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
<ContentControl Grid.Column="1" Content="{Binding CurrentPageViewModel}"/>
</Grid>