[英]Binding of a ContentControl from DataTemplate only working in constructor?
我正在尝试通过使用ICommands来切换内容控件的内容。 现在设置此属性在构造函数中有效,但在任何命令中都不起作用。
我在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}" />
这是ShellViewModel的构造函数。 正如我所说设置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");
}
}
如果我正确理解了您的问题,您可以为CurrentViewModel创建VM类,从INotifyPropertyChanged继承它并修改它的属性。 Bindng应该是单向的。
我会退后一步,给ContentControl一个名称,并尝试直接设置内容属性,看看是否有其他错误。 此外,如何为ContentControl设置DataContext? 尝试在setter上设置断点。 您还可以在输出窗口中检查Bindings上的错误。
所以我必须通过打破MVVM模式来解决这个问题。 我在shell视图模型的代码中使用了MVVM light messenger类,只需将内容控件设置为新视图,然后将其数据上下文设置为ShellViewModel的当前视图模型。
我对这个解决方案并不完全满意,但它确实能正常运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.