简体   繁体   中英

How to call CanExecute when validation cancels UpdateSourceTrigger

I am using a ValidationRule on a TextBox in my View, and that ValidationRule is working properly.

However, a problem arises when I am in the state where the canExecute method for a Command (on a Button in this case) has returned true ( Button is enabled), and then the user changes the contents of the TextBox so the ValidationRule returns a false ValidationResult . This results in the ViewModel property bound to the Button.Text not being updated, which means the canExecute method still thinks results are good and returns true.

So - how can I get the ViewModel property in question to update in spite of the false ValidationResult ? Or is there another way of doing all this?

Edit:Here is the XAML for my TextBox :

<TextBox HorizontalAlignment="Left" Margin="67,50,0,0" VerticalAlignment="Top" Width="27">
    <TextBox.Text>
        <Binding Path="MachineNo" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:MachineNoValidate/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

After doing some more research, the solution appears to be implementing the IDataErrorInfo interface on my ViewModel. I then have full access to the current contents of the TextBox through the bound property.

Here is the new XAML:

<TextBox HorizontalAlignment="Left" Margin="67,50,0,0" VerticalAlignment="Top" Width="27"
         Text="{Binding MachineNo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, 
         ValidatesOnDataErrors=True}"/>

Only this[] needs to be implemented; WPF does not use the Error property.

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