Search code examples
c#wpfbindingcommand

WPF bind to changing command


I have a button that should bind to to command of a View. The problem is that this command changes runtime (and initially it is null). My code looks like this:

MyViewModel.cs

public class MyViewModel INotifyPropertChanged
{
    ....
    private CommandStorage? _commandStorage;
    public CommandStorage? commandStorage
    {
       get => _commandStorage;
       set
       {
           _commandStorage == value;
           OnPropertyChanged(nameof(CommandStorage));
       }
    }
    public ICommand MyCommand => commandStorage?.MyStoredCommand;
    ......
 }

MyView.xaml:

<Button Command={Binding MyCommand}

What I face here is that MyCommand is sets once to null during initialization. And even after commandStorage changes new value is not set to MyCommand.


Solution

  • Bind to the CommandStorage property that you raise change notifications for and remove the superfluous MyCommand property:

    <Button Command="{Binding CommandStorage.MyStoredCommand}" />
    

    The binding engine cannot be supposed to know to refresh the value of the MyCommand property when you raise the PropertyChanged event for the CommandStorage property.

    The other option is to actually raise the event for the data-bound property in the setter of the other property:

    public CommandStorage? commandStorage
    {
        get => _commandStorage;
        set
        {
            _commandStorage == value;
            OnPropertyChanged(nameof(CommandStorage));
            OnPropertyChanged(nameof(MyCommand));
        }
    }
    

    I guess it's just a typo but in the code you have posted, the property is called commandStorage.