开发者

Binding a save command WPF

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 开发者_JAVA技巧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.


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();


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜