I am working on a sample ViewModel in WPF and I am currently binding 3 textboxes in the View to Id
, FirstName
, and LastName
. I then have a button click event in the xaml.cs file that executes a method that updates the sample database table. I am trying to wrap my head around MVVM and WPF. I want to take away the button click event and bind to a Command instead. I am using Linq to Sql for the db connection.
When I am debugging the code everything is returning null. Am I on the right path?
Thanks!
Here is part of the VM (I didnt want to post all the code.)
public class People
{
public Guid Id {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
}
private People mPeople = null;
private Guid mId = Guid.empty;
public People people
{
get {return mPeople;}
set {mPeople = value; OnPropertyChanged("people");}
}
public overide void Refresh()
{
Using (DatabaseDataContext dc = new DatabaseDataContext())
{
mId = CurrentUser.Identity;
var query = from person in dc.PeopleTables
where person.PId = mId
select new People()
{
Id = person.PId,
FirstName = person.FirstName,
LastName = person.LastName
};
mPeople = query.First();
}
}
In the VM here is what I am trying with the Commands
private RelayCommand mUserUpdate = null;
public ICommand UserUpdate
{
get
{
if(mUserUpdate == null) mUserUpdate = new RelayCommand(p => UpdateUser(p));
return mUserUpdate;
}
}
private void UpdateUser(object parameter)
{
People pe = parameter as People;
UpdateUser(pe.Id, pe.FirstName, pe.LastName);
}
public static void UpdateUser(Guid Id, string FirstName, string LastName)
{
DatabaseDataContext DC = new DatabaseDatacontext();
var User = (from c in DC.GetTable<PeopleTable>()
where c.PId = mId
select c).SingleOrDefault();
if (User == null
{
//Do my inserts here
}
else
{
try
{
User.Id = Id;
User.FirstName = FirstName;
User.LastName = LastName;
DC.SubmitChanges();
}
catch
{
throw ex;
}
}
}
Here is my click event I was using
private void btnSave_Click(object sender, RoutedEventArgs e)
{
UserViewModel.UpdateUser(txtId.Text, txtFirstName.Text, txtLastName.Text);
}
Yea, I took out the click event and replaced it with
<Button Command="{Binding Path=UserUpdate}"/>
I am binding the textboxes like this
<TextBox Width="250" Text="{Binding Path=Id}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,5,0,0">
<Label Content="First Name:" Margin="0,0,4,0"/>
<TextBox Width="250" Text="{Binding Path=FirstName}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,5,0,0">
<Label Content="Last Name:" Margin="35,0,4,0"/>
<TextBox Width="250" Text="{Binding Path=LastName}"/>