Когда я передаю аргумент в RelayCommand, почему моя связанная кнопка отключена? - PullRequest
0 голосов
/ 03 мая 2019

У меня есть кнопка, которая привязана к ViewModel с помощью RelayCommand. Мне нужно закрыть фактическое окно в связанной функции после нажатия кнопки. Но если я связываю это, кнопка отключена, и я не могу нажать на нее.

My RelayCommand.cs

using System;
using System.Windows.Input;

namespace APP.Commands
{
    public class RelayCommand : ICommand
    {
        private readonly Func<Object, Boolean> canExecuteAction;
        private readonly Action<Object> executeAction;

        public RelayCommand(Action<Object> executeAction, Func<Object, Boolean> canExecuteAction = null)
        {
            this.executeAction = executeAction;
            this.canExecuteAction = canExecuteAction;
        }

        public RelayCommand(Action executeAction, Func<Boolean> canExecuteAction = null)
            : this(p => executeAction(), p => canExecuteAction?.Invoke() ?? true)
        {
        }

        public Boolean CanExecute(Object parameter) => canExecuteAction?.Invoke(parameter) ?? true;

        public void Execute(Object parameter)
        {
            executeAction?.Invoke(parameter);
        }

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

    public class RelayCommand<T> : ICommand
    {
        private readonly Func<T, Boolean> canExecute;
        private readonly Action<T> execute;

        public RelayCommand(Action<T> execute, Func<T, Boolean> canExecute = null)
        {
            this.execute = execute;
            this.canExecute = canExecute;
        }

        public Boolean CanExecute(Object parameter)
        {
            if (parameter is T typedParameter)
            {
                return canExecute?.Invoke(typedParameter) ?? true;
            }

            return false;
        }

        public void Execute(Object parameter)
        {
            if (parameter is T typedParameter)
            {
                execute?.Invoke(typedParameter);
            }
        }

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

}

ViewModel.cs

using System.Collections.ObjectModel;
using System.Windows.Input;
using BL.Extensions;
using BL.Messages;
using BL.Models;
using BL.Repositories;
using BL.Services;
using System.Windows;
using APP.Commands;

namespace APP.ViewModels
{
    public class UserDetailViewModel
    {
        public RelayCommand<Window> Command { get; private set; }
        public UserDetailViewModel()
        {
            Command = new RelayCommand<Window>(CommandExecute);
        }

        Services.MessageBoxService msg = new Services.MessageBoxService();
        public void CommandExecute(Window window)
        {
            Views.MembersList membersList = new Views.MembersList();
            membersList.Show();
            window.Close();
        }

    }
}

1009 * XAML *

<Window x:Class="APP.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:APP"
        xmlns:viewModels="clr-namespace:APP.ViewModels"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance viewModels:UserDetailViewModel}"
        DataContext="{Binding Source={StaticResource ViewModelBaseLocator}, Path=UserDetailViewModel}"

        Title="ICS Projekt" Height="500" Width="500" ResizeMode="NoResize" WindowState="Normal" >
    <Grid Background="DeepSkyBlue">
        <Button Content="Login" Command="{Binding Path=Command, Mode=OneWay}" CommandParameter="{Binding ElementName=MainWindow}" />
   </Grid>

</Window>

После нажатия кнопки «Войти» я хочу вызвать функцию в ViewModel через Command, которая работает без Window, но если я добавлю параметр в Command, это отключит кнопку.

...