RelayCommand CanExecute behavior does not work

I am having trouble RelayCommandproperly enabling / disabling an attached control.

I have an element EventToCommandattached to a button. The command is a data binding to the ViewModel. The button is initially disabled (expected behavior), but I can not get the logic CanExecuteto check its value. When CurrentConfigFileinstalled and exists, the button must be enabled. I executed the code and checked the value of the file in debug to make sure it is installed, but the control is still disabled. I tried CommandManager.InvalidateRequerySuggested()and command.RaiseCanExecuteChanged()but it does not turn on.

I wondered if lambdas didn’t work correctly for the behavior CanExecute(although the examples use them) or that the behavior CanExecuteshould be bound to another element.

Here is my code:

// The FileInfo being checked for existence before the button should be enabled
public const string CurrentConfigFilePN = "CurrentConfigFile";
public FileInfo CurrentConfigFile
{
    get
    {
        return _currentConfigFile;
    }

    set
    {
        if (_currentConfigFile == value)
        {
            return;
        }

        var oldValue = _currentConfigFile;
        _currentConfigFile = value;

        // Update bindings, no broadcast
        RaisePropertyChanged(CurrentConfigFilePN);
    }
}

public MainViewModel()
{
    // snip //

    SaveCommand = new RelayCommand(SaveConfiguration, 
        () => CurrentConfigFile != null && CurrentConfigFile.Exists);
    }

private void SaveConfiguration()
{

    // export model information to xml document
    ExportXMLConfiguration(CurrentConfigFile);

}

and markup

<Button x:Name="SaveButton" Content="Save" Width="75" Margin="20,5">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <GalaSoft:EventToCommand x:Name="SaveETC" 
                Command="{Binding SaveCommand}" 
                MustToggleIsEnabledValue="true" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

Update:

According to Isaku Savo’s suggestion, I attached RelayCommandto the button with

<Button x:Name="SaveButton" Content="Save" Width="75" Margin="20,5" 
Command="{Binding SaveCommand}"/>

and it was turned off and turned on correctly when it was installed FileInfo. I think I must remember, so as not to fix what is not broken!

+3
source share
2 answers

Why don't you just attach to the command directly from the button?

<Button Command="{Binding SaveCommand}" Content="Save" />

Maybe the EventToCommand thing you are using is useless with notification to the CanExecute command.

CanExecute - , CanExecute , CurrentConfigFile? , , WPF CanExecute, - CommandManager, a >

EDIT: , OP .

+2

msdn :

FileInfo . Refresh, .

​​ CanExecute. , CanExecute , , IO , , .

+1

Source: https://habr.com/ru/post/1765704/


All Articles