Home > database >  How to set CanExecuteCommand correctly for WPF double TextBox?
How to set CanExecuteCommand correctly for WPF double TextBox?

Time:02-15

For this example I use Prism.WPF. I have a TextBox in my WPF and a button:

<TextBox Text="{Binding MyDoubleValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

<Button Width="200" Command="{Binding SaveParametersCommand}">Save</Button>

and the corresponsing property:

private double _myDoubleValue;
public double MyDoubleValue
{
    get { return _myDoubleValue; }
    set { SetProperty(ref _myDoubleValue, value); }
}

If the user changes the value so that a correct double value is entered, a method shall be executable:

private DelegateCommand _saveParametersCommand;

public DelegateCommand SaveParametersCommand =>
    _saveParametersCommand ?? (_saveParametersCommand
        = new DelegateCommand(ExecuteSaveParametersCommand, CanExecuteSaveParametersCommand)
                    .ObservesProperty(() => MyDoubleValue))                
                );

void ExecuteSaveParametersCommand(){ /* ... */}

void CanExecuteSaveParametersCommand(){
    // How to ensure that a correct double is inserted?
}

I have tried to convert the double to a string with "." as separator and checked for string.IsNullOrEmpty(), but this did not lead to success. How can I correctly check, if the user has entered a valid double value?

CodePudding user response:

Since C# is a strongly typed programming language, a double property such as MyDoubleValue can only be set to a valid double value. It cannot ever be set to something else ,such as for example a string.

(Only) If you change the type of the property to string, you could determine whether a valid value was given using the double.TryParse method:

private string _myDoubleValue;
public string MyDoubleValue
{
    get { return _myDoubleValue; }
    set { SetProperty(ref _myDoubleValue, value); }
}

bool CanExecuteSaveParametersCommand()
{
    return double.TryParse(_myDoubleValue, out var doubleValue);
}
  • Related