I am trying to insert an object into the database using the MVVM pattern via textboxes. The actual problem is getting the object into the ViewModel in the first place. My idea was to add the NewCustomer, of the Customer type, in the ViewModel, and then bind the textboxes to the appropriate properties. Here's what it looks like:
我试图通过文本框使用MVVM模式将对象插入数据库。实际问题是首先将对象放入ViewModel。我的想法是在ViewModel中添加Customer类型的NewCustomer,然后将文本框绑定到适当的属性。这是它的样子:
XAML:
XAML:
<Label Content="First Name:" Grid.ColumnSpan="2" Margin="10,0,325,227"/>
<TextBox Text="{Binding NewCustomer.FirstName}" Grid.Column="1" Margin="0,31,322,227"/>
<Label Content="Last Name:" Grid.ColumnSpan="2" Margin="10,74,325,158"/>
<TextBox Text="{Binding NewCustomer.LastName}" Margin="10,110,325,148" Grid.ColumnSpan="2"/>
<Label Content="Bank Balance:" Margin="10,148,325,81" Grid.ColumnSpan="2"/>
<TextBox Text="{Binding NewCustomer.BankBalance}" Grid.Column="1" Margin="0,179,322,81"/>
<Label Content="About me:" Margin="10,215,325,10" Grid.ColumnSpan="2"/>
<TextBox Text="{Binding NewCustomer.AboutMe}" Grid.Column="1" Margin="0,246,322,10"/>
<Button Margin="255,113,67,141" Content="Add" Command="{Binding AddCommand}" Grid.Column="1">
ViewModel (the important parts):
ViewModel(重要部分):
private Customer _newCustomer;
public Customer NewCustomer
{
get { return _newCustomer; }
set
{
_newCustomer = value;
RaisePropertyChanged("NewCustomer");
}
}
/.../
public void Add(object C)
{
db.Customers.Add(NewCustomer);
db.SaveChanges();
LoadCustomers();
}
public RelayCommand AddCommand { get; set; }
#endregion
But for some reason the NewCustomer property is always null (checked via debugging).
但由于某种原因,NewCustomer属性始终为null(通过调试检查)。
Any ideas? Thanks
有任何想法吗?谢谢
1 个解决方案
#1
0
It is null because no one created it,
它是null因为没有人创建它,
Use this,
用这个,
private Customer _newCustomer = new Customer();
Values should be bound correctly after
值后应正确绑定
Or another way, in ViewModel constructor do init
或者另一种方式,在ViewModel构造函数中执行init
NewCusomer = new Customer();
#1
0
It is null because no one created it,
它是null因为没有人创建它,
Use this,
用这个,
private Customer _newCustomer = new Customer();
Values should be bound correctly after
值后应正确绑定
Or another way, in ViewModel constructor do init
或者另一种方式,在ViewModel构造函数中执行init
NewCusomer = new Customer();