在WPF中为Command绑定添加多个验证

时间:2018-03-23 10:53:43

标签: wpf commandbinding

我在表单和按钮中有两个组合框。我想要做的是仅当两个组合框都选择了值时才启用该按钮。

我的xaml

    <Button Content="Generate Report" 

            Command="{Binding GenerateReportCommand}"
            Margin="30,250,0,0">

              <ComboBox Name="combo1" 
              ItemsSource="{Binding BannerValues}"
              SelectedItem="{Binding item1}">

              <ComboBox Name="combo2" 
              ItemsSource="{Binding BannerValues}"
              SelectedItem="{Binding item2}">   

我有一个视图模型,其中定义了所有绑定。

class DataSource : INotifyPropertyChanged
{

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
    public DataSource()
    {
        item1= load();
        item2=load();// have some custome function to load the values for combobox
    }
public ICommand GenerateReportCommand
    {
        get
        {
            return new CommandHandler(() => GenerateReport(item1,item2), true);
        }
    }

我有一个单独的commandhandler类,它将在一个seaprate文件中。

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

如何根据两个组合框禁用/启用按钮。在互联网上搜索发现我们可以使用multidatatrigger。但我想实现使用这个命令hanlder canexecute function

1 个答案:

答案 0 :(得分:0)

以下是对此的另一种看法:

{{1}}