我有我的Model
类实现INotifyPropertyChanged
。 我的查看有5 TextBox
,2 Button
和ListView
来显示网格。 在我的ViewModel
中,我之前在我的Model
类的ObservableCollection
中添加了默认值,并将其显示为ListView
。使用MVVM将数据保存到集合和显示WPF
该按钮的实现使用ICommand
和RelayCommand
完成。
现在我想从UI TextBox
的用户添加数据到ObservableCollection
。我怎样才能做到这一点? UI TextBox
具有Model
类的属性。
我View
<ListView Name="UserGrid" Grid.Row="1" Margin="4,178,12,13" ItemsSource="{Binding UserDatas}" >
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,7,0,0" Name="txtUserId" VerticalAlignment="Top" Width="178" Text="{Binding UserId}" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,35,0,0" Name="txtFirstName" VerticalAlignment="Top" Width="178" Text="{Binding FirstName}" />
像这些有5个文本框
的Model
类:
public class User : INotifyPropertyChanged
{
private int userId;
private string firstName;
public int UserId
{
get
{
return userId;
}
set
{
userId = value;
RaisePropertyChanged("UserId");
}
}
}
视图模型:
public class UsersViewModel:INotifyPropertyChanged
{
private ObservableCollection<User> userDatas;
public ObservableCollection<User> UserDatas
{
get
{
if (userDatas == null)
{
userDatas = new ObservableCollection<User>();
}
return userDatas;
}
set
{
userDatas = value;
RaisePropertyChanged("UserDatas");
}
}
}
private CommandBase _LoadCommand;
public ICommand LoadCommand
{
get
{
if (this._LoadCommand == null)
this._LoadCommand = new CommandBase(LoadData);
return this._LoadCommand;
}
}
private void LoadData(object obj)
{
//What need to be done here to access the textboxes of UI which are binded to User.cs class.
User newUser = new User();
UserDatas.Add(newUser);
}
现在我需要在LoadData方法写入从UI采取inputfrom文本框,并将其存储在我的ObservableCollection
使用Inotifypropertychanged。现在为文本框创建一个getter setter字符串并绑定它。现在一旦你输入了价值,就把它添加到你可观察的集合中,它应该反映出来。 – Jerin
您不应该将模型绑定到UI,因为UI应该与模型无关,只知道视图模型 – Tseng
到目前为止您有什么?你能基本证明你是如何将你的属性绑定到视图/视图模型上的吗? – Tyress