【发布时间】:2015-10-13 10:06:07
【问题描述】:
我目前正在使用 C# 涉足 WPF 我的老师知道如何使用Windows窗体,但对WPF知之甚少。我可以看到使用 GUI 的方式有点不同,但它看起来很可靠。
在完成一个小型速成课程后,我尝试使用 XAML 添加一个类作为 MainWindow 的数据上下文,但我似乎无法正确执行此操作。我在这里看到了很多关于它的帖子,但没有一个事情与我所经历的完全一样。这是我的 XAML
<Window x:Class="WPFTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFTest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:AddressBookViewModel />
</Window.DataContext>
<Grid x:Name="WPFTest">
<Button x:Name="btnNewContact" Content="Create a New Contact" HorizontalAlignment="Left" Margin="10,273,0,0" VerticalAlignment="Top" Width="209"/>
<Label x:Name="lblName" Content="Name:" HorizontalAlignment="Left" Margin="259,129,0,0" VerticalAlignment="Top"/>
<Label x:Name="lblEmail" Content="E-Mail:" HorizontalAlignment="Left" Margin="259,160,0,0" VerticalAlignment="Top"/>
<Label x:Name="lblPhone" Content="Phone:" HorizontalAlignment="Left" Margin="259,191,0,0" VerticalAlignment="Top"/>
<TextBox x:Name="txtName" HorizontalAlignment="Left" Height="23" Margin="327,133,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="txtEmail" HorizontalAlignment="Left" Height="23" Margin="327,164,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="txtPhone" HorizontalAlignment="Left" Height="23" Margin="327,195,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<ListBox x:Name="lbxContacts" HorizontalAlignment="Left" Height="204" Margin="10,53,0,0" VerticalAlignment="Top" Width="209"/>
</Grid>
还有我想用作 ViewModel 的类:
namespace WPFTest
{
public class AddressBookViewModel
{
public AddressBookViewModel()
{
}
protected List<Contact> contacts = new List<Contact>();
protected Contact selectedContact = null;
public List<Contact> Contacts
{
get
{
return contacts;
}
set
{
contacts = value;
}
}
public Contact SelectedContact
{
get
{
return selectedContact;
}
set
{
selectedContact = value;
}
}
}
}
然而,这只是给我一个错误:
The name "AddressBookViewModel" does not exist in the namespace "clr-namespace:WPFTest".
我只是不明白出了什么问题。在我看来,AddressBookViewModel 确实非常多地存在于这个命名空间中,但 Visual Studio 显然不同意。
谁能给我解释一下这个问题?
我知道我可以在后面的代码中绑定 Datacontext,但是,我可以看到能够在 XAML 中执行此操作的价值
【问题讨论】:
-
您是否尝试过构建/重建项目? Xaml 错误有时仅在构建/重建后才能解决...
-
是的,它不会改变任何东西。
-
你是把 ViewModel 类添加到解决方案中自己的文件还是添加到 Window 的代码文件中?
-
您还有其他错误吗?有时(或更经常)xaml 错误消息具有误导性。修复一切并尝试重建。我在您的定义中看不到错误,它类似于this,因此应该可以工作。除非类名中有一些不可见的字符。
-
如果您在 XAML 文件中注释掉那些 DataContext 行,您的项目构建是否正确?