简体   繁体   中英

Validate a TextBox upon button press in WPF/MVVM

I have a TextBox and a Button in my view. I have an ICommand method, String serial number property, and a IsEnabled property in my view model.

When the user clicks the Button I'd like to validate the serial number in the TextBox with the InDatabase property. If the contents in the TextBox are invalid, I would like to raise an error on the TextBox . If the contents are valid in the TextBox I'd like to disable the Button and execute the command.

Here is the view:

<StackPanel Width="Auto" Height="Auto" VerticalAlignment="Center" HorizontalAlignment="Center">
    <UniformGrid Rows="3"  >
        <TextBlock Text="This device appears to be uninitialized."/>
        <UniformGrid Rows="1" Columns="2">
            <Label>Serial Number:</Label>
            <TextBox Text="{Binding IdentifiedSerialNumber, Mode=TwoWay, ValidatesOnDataErrors=True}"></TextBox>
        </UniformGrid>
        <Button Content="Identify" Command="{Binding IdentifyCommand}" IsEnabled="{Binding CanExecuteDeviceRestoration}"/>
    </UniformGrid>
</StackPanel>

Here is the view-model:

public string IdentifiedSerialNumber 
{
    get
    {
        return this.identifiedSerialNumber;
    }
    set
    {
        this.identifiedSerialNumber = value;
    }
}

public ICommand IdentifyCommand
{
    get
    {
        return new RelayCommand(this.RelayRestoreControllerIdentity);
    }
}

public bool CanExecuteDeviceRestoration
{
    get
    {
        return canExecuteDeviceRestoration;
    }
    private set
    {
        this.canExecuteDeviceRestoration = value;
        RaisePropertyChanged("CanExecuteDeviceRestoration");
    }
}

public async void RelayRestoreControllerIdentity()
{
    await Task.Run(
    () =>
    {
        this.RestoreControllerIdentity();
    });
}

public bool InDatebase
{
    get
    {
        return DatabaseConnection.DeviceExists(this.IdentifiedSerialNumber);
    }
}

My question is how do I bind the behavior such that when the user click the Button the TextBox is validated, and if it fails it displays an error with a message and if it passes the Button will be disabled and the command will execute.

You need to implement IDataErrorInfo.
This would add an indexer which returns a string.
If empty string is returned it means no error.
You can return an empty string until button is pressed(u could use a flag).
when button is pressed,Run the validation logic and appropriately change the flag and Raise PropertyChanged event for IdentifiedSerialNumber
You can learn how to implement IDataErrorInfo from here .
Also you need to Raise PropertyChanged event for IdentifiedSerialNumber.

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