关于c#:如何将WPF按钮绑定到ViewModelBase中的命令?

How to bind WPF button to a command in ViewModelBase?

我有一个视图AttributeView,其中包含各种属性。 还有一个按钮,当按下该按钮时,应将默认值设置为属性。 我还有一个ViewModelBase类,它是我拥有的所有ViewModel的基类。
问题是我似乎无法使用WPF将按钮绑定到命令。

我已经尝试过了,但是它什么也没做:

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

如下定义命令(在ViewModelBase中):

1
public CommandBase DataInitialization { get; protected set; }

在应用程序启动时,将为命令创建一个新实例:

1
DataInitialization = new DataInitializationCommand()

但是,WPF绑定似乎无法"找到"命令(按按钮不会执行任何操作)。 当前视图中使用的ViewModel源自ViewModelBase。 我还能尝试什么(我对WPF还是很陌生,所以这可能是一个非常简单的问题)?


1
2
3
4
5
6
 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

窗口后面的代码:

1
2
3
4
5
6
7
8
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

ViewModel:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc.
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

命令处理程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

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

我希望这会给你这个主意。