I have a window with 3 textboxes in a grid -this is my view- and I have Save button to add a new user to my user list with the datas from the textboxes. I want to use a relay command to do this on my viewmodel class but I am quite confused with how to make the bindings. I hope it's clear enough. Any ideas, or examples will be helpful. thanks in advance.
+1
A:
You should have a ViewModel something like the following :
class UserViewModel
{
public String Name { get; set; }
public String Password { get; set; }
public String Email { get; set; }
public RelayCommand AddUserCommand { get; set; }
public UserViewModel()
{
AddUserCommand = new RelayCommand(AddUser);
}
void AddUser(object parameter)
{
// Code to add user here.
}
}
And you can use it like following :
<StackPanel>
<TextBox Text="{Binding Name}"></TextBox>
<TextBox Text="{Binding Password}"></TextBox>
<TextBox Text="{Binding Email}"></TextBox>
<Button Command="{Binding AddUserCommand}">Add</Button>
</StackPanel>
To make this work, put following code in your UserControl/Control/Window's constructor :
DataContext = new UserViewModel();
decyclone
2010-08-04 08:46:56
Are those codes enough to supply the relationship between view and viewmodel? it still doesn't work...
cemregoksu
2010-08-04 10:10:08
You have to create an object of the ViewModel and to assign it to the DataContext of the window
Zied
2010-08-04 11:37:43
Thanks Zied for adding to that. I have updated the code.
decyclone
2010-08-04 14:18:13
yes, assigning the datacontext was the lack of my code. thanks=)
cemregoksu
2010-08-12 11:46:51
A:
I presume that you read Josh Smith article: WPF Apps With The Model-View-ViewModel Design Pattern. If you didn't, then read it first, and then download code, because example is very similar to your problem.
zendar
2010-08-04 08:48:56
I understand you :). Been there. I got parts of it after third reading and studying code. Needs time to catch what's happening. At least I needed.
zendar
2010-08-04 10:57:39
A:
Did you created an instance of the ViewModel and putted this instance in the DataContext of your view or stackpanel?
example:
UserViewModel viewModel = new UserViewModel(); UserWindow view = new UserWindow(); view.DataContext = viewModel; view.Show();
There are several options on coupling the View and the Viewmodel:
- Create the View and ViewModel and set the ViewModel to the DataContext property (code above)
- Create the ViewModel in the constructor of the View and fill the DataContext property with it
- Create a Resource in your view of the type of your ViewModel and fill the DataContext property in XAML
I prefer the first option because you can combine the Views and Viewmodels as you like at runtime.
Hopefully this is a helpfull answer.
Wouter Janssens - Xelos bvba
2010-08-04 11:33:28