我一直在按照教程创建一个在C#/Windows手机上工作的MVVM原型。这是我的主要。但是我得到的错误是ExampleMvvmPhone.ViewModel
是一个namespace
但像type
一样使用。请在这里协助我。谢谢
namespace ExampleMvvmPhone
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
ViewModel viewModel = new ViewModel();
this.DataContext = viewModel;
}
}
}
我的 xaml
<TextBox x:Name="txtFirstName" Grid.Column="2" Grid.Row="2" Margin="0,0,0,5" FontSize="24" Text="{Binding Current.FirstName, Mode=TwoWay}"/>
<TextBox x:Name="txtLastName" Grid.Column="2" Grid.Row="3" Margin="0,0,0,5" FontSize="24" Text="{Binding Current.LastName, Mode=TwoWay}"/>
<TextBox x:Name="txtEmail" Grid.Column="2" Grid.Row="4" Margin="0,0,0,5" FontSize="24" Text="{Binding Current.Email, Mode=TwoWay}"/>
<TextBox x:Name="txtPhone" Grid.Column="2" Grid.Row="5" Margin="0,0,0,5" FontSize="24" Text="{Binding Current.Phone, Mode=TwoWay}"/>
我的视图模型类:
namespace ExampleMvvmPhone.ViewModel
{
public class ViewModel
{
private List<Customer> customers;
private int currentCustomer;
//constructor
public ViewModel()
{
this.currentCustomer = 0;
this.customers = new List<Customer>
{
new Customer
{
CustomerID = 1,
Title = "Mr",
FirstName = "Mwangi",
LastName = "Austin",
Email = "mwangi@gmail.com",
Phone = "0728704660"
},
new Customer
{
CustomerID = 2,
Title = "Mrs",
FirstName = "Christine",
LastName = "Nekunda",
Email = "mwangi@gmail.com",
Phone = "0728704660"
},
new Customer
{
CustomerID = 3,
Title = "Ms",
FirstName = "Catherine",
LastName = "Nakutenga",
Email = "mwangi@gmail.com",
Phone = "0728704660"
}
};
}
public Customer Current
{
get
{
return this.customers[currentCustomer];
}
}
}
}
问题出在这一行:
ViewModel viewModel = new ViewModel();
由于您位于不同的命名空间中,因此应包含 中定义的命名空间 ViewModel 与 using
:
using ExampleMvvmPhone.ViewModel;
namespace ExampleMvvmPhone
{
...
或者使用将其添加到类名:
ViewModel.ViewModel viewModel = new ViewModel.ViewModel();
似乎错误准确地告诉您问题是什么:
"exampleMvvmPhone.ViewModel"是一个"命名空间",但像"类型"一样使用
如果您查看代码,则会看到已将命名空间和类名命名为 ViewModel
。更改此设置:
namespace ExampleMvvmPhone.ViewModel
{
public class ViewModel
{ ...
对此:
namespace ExampleMvvmPhone
{
public class ViewModel
{
...
在 ViewModel
类中,将命名空间namespace ExampleMvvmPhone.ViewModel
更改为仅namespace ExampleMvvmPhone
。 因为如果您将namespace ExampleMvvmPhone.ViewModel
用于ViewModel
类,那么编译器会混淆ViewModel
是class
还是namespace
。
谢谢