所以我有一个问题。 我尝试使用MVVM模式将数据保存到一个人类,我想,这应该很容易 - 我是一个绝对的初学者。我已经有2个视图,2个MainViewModels和2个命令(添加和删除,删除工作正常)。
当我启动我的应用程序时,可以按下添加按钮并打开一个新窗口。我可以在文本框中输入一些数据,如名称,金额和价格。现在我需要一种简单的方法来保存我的Observable Collection中的数据。那我该怎么做呢?
我的想法,点击保存按钮后,一个方法被调用(构造函数),我将数据保存在我的可观察集合中,但我该如何实现这个方法?
MainViewModel
class MainViewModel : BaseViewModel
{
ObservableCollection<Software> Data;
Software selected;
public Software Selected
{
get { return selected; }
set { selected = value; }
}
public ObservableCollection<Software> swdata
{
get { return Data; }
set { Data = value; }
}
#region ATTRIBUTES
private double purchaseprice;
private String name;
private double salesprice;
#endregion
#region CONSTRUCTOR
public String Name
{
get { return selected.Name; }
set
{
selected.Name = value;
OnPropertyChanged("Name");
}
}
public double Purchaseprice
{
get { return selected.PurchasePrice; }
set
{
selected.PurchasePrice = value;
OnPropertyChanged("Purchaseprice");
}
}
public double Salesprice
{
get { return selected.SalesPrice; }
set
{
selected.SalesPrice = value;
OnPropertyChanged("Salesprice");
}
}
#endregion
public MainViewModel()
{
Data = LoadSample();
}
public ICommand AddItem { get; set; }
public ICommand DeleteItem { get; set; }
public ObservableCollection<Software> LoadSample()
{
this.AddItem = new AddCommand(this);
this.DeleteItem = new DeleteCommand(this);
if (Data == null)
{
Data = new ObservableCollection<Software>();
Data.Add(new Software("1") { Name = "Adobe Photoshop", SalesPrice = 199, PurchasePrice = 249 });
Data.Add(new Software("2") { Name = "Adobe Elements", SalesPrice = 179, PurchasePrice = 219 });
Data.Add(new Software("3") { Name = "Adobe Indesign", SalesPrice = 299, PurchasePrice = 349 });
Data.Add(new Software("3") { Name = "Microsoft Office", SalesPrice = 199, PurchasePrice = 249 });
Data.Add(new Software("3") { Name = "SQL Developer ", SalesPrice = 79, PurchasePrice = 129 });
Data.Add(new Software("3") { Name = "Microsoft Windows 7", SalesPrice = 89, PurchasePrice = 99 });
}
return Data;
}
}
AddCommand
class AddCommand : ICommand
{
//Call MainViewModel
#region MVM CALL
private readonly MainViewModel pMainViewModel;
#endregion
#region MVM CONSTRUCTOR
public AddCommand(MainViewModel xMainViewModel)
{
pMainViewModel = xMainViewModel;
}
#endregion
#region CANEXECUTE
public bool CanExecute(object parameter)
{
return (pMainViewModel.Selected != null);
}
#endregion
#region EVENTHANDLER
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
var dialog = new AddView()
{
// Owner = this,
DataContext = null
};
dialog.ShowDialog();
}
#endregion
}