How to Re-Evaluate CanExecute in a DelegateCommand

41 Views Asked by At

I Have a table in SQL Server with some rows. I have a Prism MVVM project in WPF and Some textbox in which Text of each is bind to a property of my table.

When I Write some thing in textboxes, canExecute command not fired. Why?

For examle in View:

<TextBox Text="{Binding UserModel.Fname, 
    UpdateSourceTrigger=PropertyChanged, 
    ValidatesOnDataErrors=True, Mode=TwoWay}" />

and a button with commad: Command="{Binding Add_EditUserInfo}"

in Viewmodel, I have a propert for my table:

private TblUserInfo _userModel = new TblUserInfo();
public TblUserInfo UserModel
{
    get { return _userModel; }
    set
    { 
        SetProperty(ref _userModel, value);
        Add_EditUserInfo.RaiseCanExecuteChanged();
    }
}

and for button:

public DelegateCommand Add_EditUserInfo { get; set; }

and in constructor:

Add_EditUserInfo = new DelegateCommand(OnAdd_EditUserInfo, CanAdd_EditUserInfo)
                           .ObservesProperty(() => UserModel);

for canExecute:

private bool CanAdd_EditUserInfo()
{
    return UserModel.TblUserInfo_IsValid;
}
1

There are 1 best solutions below

2
On

Your UserModel property does not change, thus no RaiseCanExecuteChanged.

You have to do that inside Fname's setter or attach a handler to _userModel.PropertyChanged and call Add_EditUserInfo.RaiseCanExecuteChangedfrom there.

When going for the handler-option, keep an eye on the lifetimes of your objects, because you might introduce a memory leak.