简体   繁体   中英

WPF MVVM and Commands

I am trying to create a WPF application taking advantage of Commands but I am having an issue with commands enabling menu buttons. I am doing some simple validation, in this case, the "Save" button is disabled until the user creates a new document or loads an existing one.

Lets say my View Model looks like this where the object ViewModel inherits INotifyPropertyChanged:

public ViewModel()
{
    New = new RelayCommand( OnNew, CanNew );
    Save = new RelayCommand( OnSave, CanSave );
}

ICommand m_cmdNew;

public ICommand New
{
    get { return m_cmdNew; }
    set
    {
        m_cmdNew = value;
        OnPropertyChanged( "New" );
    }
}

void OnNew( object param )
{
    bCanSave = true;
    // I read that this could resolve my problem.
    CommandManager.InvalidateRequerySuggested();
}

bool CanNew(  object param )
{
    return true;
}

Lets assume I am doing the same thing for a "Save" Command as well, the only exception being the "CanSave" looks like this:

bool CanSave( object param )
{
    return bCanSave;
}

My Xaml:

<Menu>
    <MenuItem Header="Text">
        <MenuItem Header="New" Command="{Binding New}"/>
        <MenuItem Header="Save" Command="{Binding Save}"/>
    </MenuItem>
</Menu>

The problem that I am having is that the CanSave method is never called after I change the variable "bCanSave". How can I accomplish this? I know I can simply create a property and using INotifyPropertyChanged and XAML binding, I can simply toggle the IsEnabled property, but that seems like a lot of work when from what I read, commands already do this.

You need to raise the CanExecuteChanged event on the command you want reevaluated, in this case that should be done when that horrible hungarian bool changes.

(I would recommend making the command fields readonly and the properties get -only, commands don't usually change)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM