Poyatoo
Poyatoo

Reputation: 104

WPF Binding ICommand with ViewModel

ICommand:

public class CMDAddEditUser : ICommand
{
    public event EventHandler CanExecuteChanged;
    public VMAddEditUser ViewModel { get; set;}

    public CMDAddEditUser()
    {
    }

    public CMDAddEditUser(VMAddEditUser vm)
    {
        ViewModel = vm;
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }


    public void Execute(object parameter)
    {
        this.ViewModel.SimpleMethod();
    }
}

ViewModel:

public class VMAddEditUser
{
    private Employee _employee = new Employee();
    private CMDAddEditUser Command { get; set; }

    public VMAddEditUser()
    {
        Command = new CMDAddEditUser(this);
    }

    public string txtFirstName
    {
        get { return _employee.FirstName; }
        set { _employee.FirstName = value; }
    }

    public void SimpleMethod()
    {
        txtFirstName = "abc";
    }
}

XAML:

<Window x:Class="WPF.AddEditUserView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:ViewModel;assembly=ViewModel"
        Title="AddEditUserView" Height="392.329" Width="534.143">
    <Grid Margin="0,0,2,-3">
        <Grid.Resources>
            <vm:VMAddEditUser x:Key="abx"/>
        </Grid.Resources>
        <Grid.DataContext>
            <vm:VMAddEditUser/>
        </Grid.DataContext>
        <Button x:Name="btn" Content="Cancel" Command="{Binding SimpleMethod, Source={StaticResource abx}}"/>

    </Grid>
</Window>

The CMDAddEditUser and VMAddEditUser is in the same project while the xaml is in a different project.

The .Execute(Object Parameter) of the ICommand doesn't seem to work. I can't bind the SimpleMethod with the button that I have. When I type the Command Binding in the xaml file, the auto-complete/suggestions only shows the txtFirstName and not the SimpleMethod. I can't figure out why the SimpleMethod can't be binded and can't be found. What did I do wrong in this code?

Upvotes: 0

Views: 1202

Answers (1)

Vladimir Djurdjevic
Vladimir Djurdjevic

Reputation: 196

First: All properties you want your view to be able to bind to, must be public. Since view binds to property, which is instance of ICommand implementation, property must be public, so view can access it. However, your SimpleMethod() can be private if you don't wanna expose it to the outside world, that why you have command calling it instead of letting view directly call it. Second: You set you grids DataContext to your 'VMEditUser' class, so in binding there is no need to specify Source, DataContext is source.

Upvotes: 0

Related Questions