I am trying to save new form data back to the database using the MVVM pattern. I have a model named Person and in my PersonViewModel I can add values to my form successfully by doing this
public void LoadPerson()
{
Person p = new Person();
p.LastName = "Servo";
p.FirstName = "Tommy";
p.Address = "123 Main St";
p.City = "Somewhere";
p.State = "MI";
p.ZipCode = "55555";
CurrentPerson = p;
}
The rest of my ViewModel looks like this
public PersonViewModel()
{
LoadCommand = new RelayCommand(LoadPerson);
SaveCommand = new RelayCommand(SavePerson);
OpenCommand = new RelayCommand(OpenPerson);
EncryptCommand = new RelayCommand(EncryptPerson);
DecryptCommand = new RelayCommand(DecryptPerson);
}
private Person currentPerson;
public Person CurrentPerson
{
get { return currentPerson; }
set
{
if (value != currentPerson)
{
currentPerson = value;
RaisePropertyChanged();
}
}
}
public ICommand DecryptCommand { get; private set; }
public ICommand EncryptCommand { get; private set; }
public ICommand LoadCommand { get; private set; }
public ICommand OpenCommand { get; private set; }
public ICommand SaveCommand { get; private set; }
So with that I can get data to the form with the LoadCommand. I can save changes back to the database successfully if I change any of the form data with the SaveCommand (when I use the LoadCommand). What I cant do is to save data when there is no data on the form to start with.
Edit To clarify I mean that when I fill the form out field by field manually after it opens the data I enter does not get saved. Since I can save changed data (LoadCommand to put the dummy data in) after I fill the form. I am sure it is because I am not doing the right thing to bind the text fields to the ViewModel when the form first opens.
The LoadCommand is creating the link, which is why that data gets saved. I think, specifically, my problem is that the SaveCommand is not creating a link when one isn't created with the LoadCommand. End Edit
I am checking for a null CurrentPerson so that I can fill it when I don't load it using the LoadCommand but I can't figure out how to hydrate it without an initial load. How do I make the Currentperson equal the form data in the code block below? (assuming that is where I do it)
if (CurrentPerson == null)
{
//Person person = CurrentPerson;
//CurrentPerson = this.currentPerson;
//string fn = CurrentPerson.FirstName;
//Console.WriteLine(fn);
//Person person = new Person();
//person.FirstName = ;
//CurrentPerson = person;
}
The answer was embarrassingly simple. I needed to add the following to the constructor
Person p = new Person();
CurrentPerson = p;