gpt4 book ai didi

wpf - MVVM DataTemplate 绑定(bind)问题

转载 作者:行者123 更新时间:2023-12-03 10:40:32 35 4
gpt4 key购买 nike

也许这是感冒药太多的例子,但我似乎无法正确地得到这个绑定(bind)。

这是(简化的)窗口,每个 ViewModel 类型都有一个 DataTemplate,它应该只显示一个关联的 View :

<Window ...>
<Window.Resources>
<DataTemplate DataType="{x:Type local:DefaultViewViewModel">
<local:DefaultView />
</DataTemplate>

<DataTemplate DataType="{x:Type other:AnotherViewModel">
<other:AnotherView />
</DataTemplate>
</Window.Resources>

<Grid>
<ContentControl Content="{Binding CurrentViewModel}" />
</Grid>
</Window>

下面是一些 MainViewModel(为简洁起见,实际的 ShowABCView 方法是比此处显示的更多功能的命令函数):
class MainViewModel : ViewModelBase
{
private Stack<ViewModelBase> mContentViewStack;

public MainViewModel()
{
mContentViewStack = new Stack<ViewModelBase>();
ShowDefaultView();
}

public ViewModelBase CurrentViewModel
{
get { return mContentViewStack.Peek(); }
}

private ShowDefaultView()
{
DefaultViewViewModel viewModel = new DefaultViewViewModel();
mContentViewStack.Push(viewModel);
NotifyPropertyChanged("CurrentViewModel");
}

private ShowAnotherView()
{
AnotherViewModel viewModel = new AnotherViewModel();
mContentViewStack.Push(viewModel);
NotifyPropertyChanged("CurrentViewModel");
}
}

和 MainWindow 启动代码:
public MainWindow()
{
this.DataContext = new MainViewModel();
}

当我运行它时,我得到了错误

System.Windows.Data.Error: 40: BindingExpression path error: 'Content' property not found on 'object' 'DefaultViewViewModel'



我知道我在这里遗漏了一些明显的东西,但是 Nyquil 和 friend 们背叛了我……

*编辑 - DefaultViewViewModel 和 DefaultView *

默认 View View 模型:
// ViewModelBase is basically just a wrapper for INotifyPropertyChanged,
// plus some other common-to-my-project properties
// (NOT INCLUDING A Content PROPERTY)
class DefaultViewViewModel : ViewModelBase
{
public DefaultViewViewModel() : base()
{
}
}

默认 View :
<UserControl ...>
<TextBlock Text="Some Hard Coded Text Formatted To My Liking" />
</UserControl>

最佳答案

好吧,您还没有显示 DefaultViewViewModel 的代码
但我的猜测是您将“内容”定义为字段而不是属性。

为了确保它会修复它,继续通过使 Content 成为依赖属性来过度杀伤它
希望有帮助

关于wpf - MVVM DataTemplate 绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4718078/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com