【发布时间】:2014-12-03 10:42:44
【问题描述】:
当我继续尝试创建一个简单的示例时,我在使用 MVVM 概念处理 DataTemplates 时遇到了很多问题。
为了熟悉DataTemplates,思路如下。只需创建一个包含绑定到我的视图模型的内容(在本例中为显示名称的标签和显示年龄的按钮)的 DataTemplate。
问题之前,这里是代码。
App.xaml.cs
namespace tutorial
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private MainWindow mw;
private ViewModel vm;
private void Application_Startup(object sender, StartupEventArgs e)
{
vm = new ViewModel();
mw = new MainWindow();
mw.DataContext = ?
mw.Activate();
mw.Show();
}
}
}
ViewModel.cs
namespace tutorial
{
class ViewModel
{
private String name;
private int age;
public ViewModel()
{
Debug.WriteLine("Hello World!");
name = "Hello World";
}
public int Age
{
get {return age;}
set {age = value;}
}
public String Name
{
get {return name;}
set {name = value;}
}
}
}
Button.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:tutorial">
<DataTemplate DataType="{x:Type local:ViewModel}">
<StackPanel>
<Label Content="{Binding ??}" />
<Button Content="{Binding ???}" />
</StackPanel>
</DataTemplate>
</ResourceDictionary>
MainWindow.xaml
<Window x:Class="tutorial.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<ContentControl Content="{Binding}" />
</Window>
所以我有以下问题:
以下代码行<DataTemplate DataType="{x:Type local:ViewModel}"> 显示名称 ViewModel 不存在于命名空间中,显然是正确的?还是我错过了什么?解决方案资源管理器的图像如下所示:
第二个问题更重要,它也表明我现在知道如何将视图绑定到视图模型。 App.xaml.cs、Button.xaml 中的问号以及 MainWindow.xaml 中可能出现的一些错误,因为我不知道 MainWindow 是如何知道的我希望它显示哪些内容。
感谢您的帮助。
这里是给整个项目的link,作为对之前cmets的回应:
【问题讨论】:
-
将您的 ViewModel 设置为公开,它应该可以工作
-
很抱歉,它没有解决第一个问题。它似乎仍然无法找到 ViewModel。
-
资源字典资源在哪里,我猜它的app.xaml..是吗??