我试图通过使用ICommands切换内容控件的内容。现在设置此属性在构造函数中工作,但不在任何命令中。来自DataTemplate的ContentControl的绑定只能在构造函数中使用?
我有这个在我的App.xaml
<Application.Resources>
<vm:ViewModelLocator x:Key="Locator"
d:IsDataSource="True" />
<DataTemplate DataType="{x:Type vm:HomeViewModel}">
<views:HomeView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:DeviceViewModel}">
<views:DeviceView />
</DataTemplate>
</Application.Resources>
这是从ShellView.xaml片段(这是它包含内容控制我想更改视图):
<ContentControl Content="{Binding Path=CurrentViewModel}" />
此处显示按钮绑定的另一个代码片段:
<Button Content="Button"
Height="23"
Name="button2"
Width="75"
Command="{Binding Path=DeviceViewCommand}" />
这里是ShellView的构造函数模型。正如我所说的设置CurrentViewModel在这里工作。 (你会注意到我设置了设备,然后回家作为测试。)
public ShellViewModel()
{
CurrentViewModel = ShellViewModel._deviceViewModel;
CurrentViewModel = ShellViewModel._homeViewModel;
HomeViewCommand = new RelayCommand(() => ExecuteHomeViewCommand());
DeviceViewCommand = new RelayCommand(() => ExecuteDeviceViewCommand());
LogOut = new RelayCommand(() => LogOutExecute(),() => true);
}
private void ExecuteDeviceViewCommand()
{
CurrentViewModel = ShellViewModel._deviceViewModel;
}
我在这里做错了什么?
这也是为当前视图模型更改的属性。应该早些时候添加这个。
public ViewModelBase CurrentViewModel
{
get
{
return _currentViewModel;
}
set
{
if (_currentViewModel == value)
return;
_currentViewModel = value;
RaisePropertyChanged("CurrentViewModel");
}
}
它看起来像你使用MVVM,但我可能是错的,但我只是想说我还没有得到。不过,我很好奇,如果CurrentViewModel是一个依赖属性或触发器PropertyChanged? – Silvermind 2012-03-11 23:24:16
我是的,我会标记它,但它似乎并不是一个特定的MVVM问题。我已经在上面添加了PropertyChanged代码。 – benjgorman 2012-03-11 23:30:47
这里的代码看起来都是正确的。你有没有在ExecuteDeviceViewCommand中设置一个断点来验证它是在button2上被调用的? – 2012-03-12 01:29:27