How to bind WPF button to a command in ViewModelBa

2019-01-02 20:37发布

I have a view AttributeView that contains all sorts of attributes. There's also a button that when pressed, it should set the default values to the attributes. I also have a ViewModelBase class that is a base class for all ViewModels I have. The problem is I can't seem to get the button bound to the command with WPF.

I've tried this, but it just doesn't do anything:

<Button Command="{Binding DataInitialization}" Content="{x:Static localProperties:Resources.BtnReinitializeData}"></Button>

The command is defined (in the ViewModelBase) like this:

public CommandBase DataInitialization { get; protected set; }

and on application startup a new instance is created for the command:

DataInitialization = new DataInitializationCommand()

However, the WPF binding doesn't seem to "find" the command (pressing the button does nothing). The ViewModel used in the current view is derived from the ViewModelBase. What else I can try (I'm quite new to WPF so this might be a very simple question)?

1条回答
梦寄多情
2楼-- · 2019-01-02 21:25
 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

And the ViewModel:

public class ViewModelBase
{
    public ViewModelBase()
    {
        _canExecute = true;
    }
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), _canExecute));
        }
    }
    private bool _canExecute;
    public void MyAction()
    {

    }
}
public class CommandHandler : ICommand
{
    private Action _action;
    private bool _canExecute;
    public CommandHandler(Action action, bool canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

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

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

查看更多
登录 后发表回答