关于命令:WPF MVVM RelayCommand操作,canExecute,参数

WPF MVVM RelayCommand Action, canExecute, parameter

我正在使用MVVM,我已经在按钮中定义了一个Command。 我想在此Command中使用一个参数,执行一个动作并证明Canexecute是否可以执行。

我有这个RelayCommand

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class RelayCommand< T > : ICommand
    {
        private readonly Action< T > _execute;
        private readonly Func<T, bool> _canExecute;

        /// <summary>
        /// Initializes a new instance of the RelayCommand class that
        /// can always execute.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <exception cref="ArgumentNullException">If the execute argument is null.</exception>
        public RelayCommand(Action< T > execute)
            : this(execute, null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the RelayCommand class.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        /// <exception cref="ArgumentNullException">If the execute argument is null.</exception>
        public RelayCommand(Action< T > execute, Func<T, bool> canExecute)
        {
            if (execute == null)            
                throw new ArgumentNullException("execute");

            _execute = execute;

            if (canExecute != null)            
                _canExecute = canExecute;            
        }

        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)            
                return true;

            if (parameter == null && typeof(T).IsValueType)
                return _canExecute(default(T));

            return _canExecute((T)parameter);            
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }

        #endregion
    }

用这个按钮

1
2
3
4
5
<Button Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2"
        Style="{StaticResource BotonSelect}" Width="200"
        Command="{Binding ModificarLicenciaCommand}"                          >
        <Label Content="Modificar Licencia" />
</Button>

并在视图模型中。

1
2
3
4
5
6
7
8
9
10
11
12
ModificarLicenciaCommand = new RelayCommand(ModificarLicencia, CanModificarLicencia);

private bool CanModificarLicencia()
{
   // Comprobar puedo modificar                            
   return true;
}

private void ModificarLicencia()
{
    // Modificar licencia
}

没关系,但是我想传递一个参数并使用类似这样的东西:

CommandParameter =" {Binding ElementName = DataGridLicencias}"

1
2
3
4
5
6
<Button Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2"
    Style="{StaticResource BotonSelect}" Width="200"
    Command="{Binding ModificarLicenciaCommand}"
    CommandParameter="{Binding ., ElementName=DataGridLicencias}">
    <Label Content="Modificar Licencia" />
</Button>

并在viewModel中:

RelayCommand

1
2
3
4
5
6
ModificarLicenciaCommand = new RelayCommand<SfDataGrid>(ModificarLicencia, CanModificarLicencia);

private void ModificarLicencia(SfDataGrid dataGrid)
{
    // Modificar licencia
}

编辑:

有了这个,我在ModificarLicenciaCommand = new RelayCommand(ModificarLicencia,CanModificarLicencia)中出现错误

在CanModificarLicentia ==>错误参数2中:无法从"方法组"转换为" Func"

有什么帮助吗?


以下视图模型实现应起作用:

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 ViewModel
{
    public ViewModel()
    {
        ModificarLicenciaCommand = new RelayCommand<SfDataGrid>(ModificarLicencia, CanModificarLicencia);
    }

    private ICommand _modificarLicenciaCommand;
    public ICommand ModificarLicenciaCommand
    {
        get { return _modificarLicenciaCommand; }
        set { _modificarLicenciaCommand = value; }
    }

    private void ModificarLicencia(SfDataGrid dataGrid)
    {
        // Modificar licencia
    }

    private bool CanModificarLicencia(SfDataGrid dataGrid)
    {
        return true;
    }
}


例如,您有一个Button和一个TextBox。
仅当文本框的文本不为空时,该按钮才会启用:
在视图中:

1
2
<TextBox Name="txtCondition" Width="120" Height="35"/>
<Button Width="120" Height="35" Content="Click me!" Command="{Binding YourICommand}" CommandParameter="{Binding ElementName=txtCondition,Path=Text}">

在ViewModel中:

1
public ICommand YourICommand { get; set; }
1
2
3
4
YourICommand = new RelayCommand<string>((str) =>
              {
                 MessageBox.Show(str);
              },(str) => { return !string.IsNullOrEmpty(str); });

享受您的代码!