![](/img/trans.png)
[英]UserControl with datatemplated ContentControl throws binding errors when its DataContext changes
[英]Binding ViewModel to ContentControl as its DataContext
我想在按钮点击时改变UserControls(我不会在这里复杂化,所以我只提到重要的部分)。 因此,想法是将这些UserControl的ViewModels绑定到ContentControl,然后使用DataTemplates将它们关联起来。 这是代码:
<Window x:Class="Project.MainWindow">
<Window.Resources>
<DataTemplate DataType="{x:Type UserControl:ViewUserControlViewModel}" >
<UserControl:ViewUserControl/>
</DataTemplate>
<DataTemplate DataType="{x:Type UserControl:EditUserControlViewModel}" >
<UserControl:EditUserControl/>
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl DataContext="{Binding UserControlViewModel}" />
<Button Content="View" Click="ChangeToView()"/>
<Button Content="Edit" Click="ChangeToEdit()"/>
</Grid>
</Window>
视图模型:
public class MainWindowViewModel : DependencyObject
{
public DependencyObject UserControlViewModel
{
get { return (DependencyObject)GetValue(UserControlViewModelProperty); }
set { SetValue(UserControlViewModelProperty, value); }
}
public static readonly DependencyProperty UserControlViewModelProperty =
DependencyProperty.Register("UserControlViewModel", typeof(DependencyObject), typeof(MainWindowViewModel), new PropertyMetadata());
public MainWindowViewModel()
{
UserControlViewModel = new EditUserControlViewModel();
}
}
但这是一个问题。 当我开始项目时,我只看到按钮而不是任何UserControls。 我做错了什么?
如果您的Window.DataContext
已正确设置为MainWindowViewModel
则应执行此任务
<ContentControl Content="{Binding UserControlViewModel}" />
在执行mvvm时,您的viewmodel应该实现INotifyPropertyChanged而不是从DependencyObject继承。
public class MainWindowViewModel : INotifyPropertyChanged
{
private object _currentWorkspace; //instead of object type you can use a base class or interface
public object CurrentWorkspace
{
get { return this._currentWorkspace; }
set { this._currentWorkspace = value; OnPropertyChanged("CurrentWorkspace"); }
}
public MainWindowViewModel()
{
CurrentWorkspace= new EditUserControlViewModel();
}
//todo: to switch the workspace, create DelegeCommand/RelayCommand and set the CurrentWorkspace
//if you don't know about these commands let me know and i post it
public ICommand SwitchToViewCommand {get{...}}
public ICommand SwitchToEditCommand {get{...}}
}
xaml:您应该将Content Property设置为CurrentWorkspace。
<ContentPresenter Content="{Binding UserControlViewModel}" />
<Button Content="View" Comamnd="{Binding SwitchToViewCommand}"/>
<Button Content="Edit" Comamnd="{Binding SwitchToEditCommand}"/>
! 不要忘记将窗口的DataContext设置为MainWindowViewModel实例。
首先,您应该发布UserControl的代码,因为(在上面的代码片段中)它负责显示一些数据。
其次,你没有绑定代码中的任何内容。
第三,ViewModel的实现是错误的。 您不需要继承DependencyObject,而是实现INotifyPropertyChanged接口,以便建立能够通知View的ViewModel。
第四,我不知道你在做什么
<ContentControl DataContext="{Binding UserControlViewModel}" />
也许你可以进一步解释?
第五,当实现MVVM模式(你目前没有做什么)时,你应该避免使用像click事件这样的事件而是使用命令。
(我知道这还不是一个真正的答案,但我不想写评论语法)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.