如何在按钮单击命令上使用验证规则
How to use Validation Rule on Button Click Command
我有一个采用单向模式的文本框,因此不会自动进行验证。
<TextBox.Text>
<Binding Path="SelectedValue.Customername"
ElementName="customerListBox"
Mode="OneWay"
>
<Binding.ValidationRules>
<validators:NameValidator ValidatesOnTargetUpdated="True"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
我有一个按钮 :
<Button Content="Save" Command="{Binding SaveCommand}"/>
现在在 ViewModel 上,我想在执行任何其他操作之前验证文本输入:
SaveCommand = new RelayCommand(
param=>
{
//If validation is true
//Then Execute Res
}
);
放弃 UI 验证规则并让您的 VM 实施 IDataErrorInfo and INotifyDataErrorInfo。
考虑一下——除非您的 VM 中的数据有效,否则您的保存命令不应执行。这意味着验证逻辑应该在您的 VM 中,而不是在您的 UI.
中
实现这些接口使得检查您是否execute/can 执行并在 CanExecute 更改时触发适当的事件变得微不足道。
我有一个采用单向模式的文本框,因此不会自动进行验证。
<TextBox.Text>
<Binding Path="SelectedValue.Customername"
ElementName="customerListBox"
Mode="OneWay"
>
<Binding.ValidationRules>
<validators:NameValidator ValidatesOnTargetUpdated="True"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
我有一个按钮 :
<Button Content="Save" Command="{Binding SaveCommand}"/>
现在在 ViewModel 上,我想在执行任何其他操作之前验证文本输入:
SaveCommand = new RelayCommand(
param=>
{
//If validation is true
//Then Execute Res
}
);
放弃 UI 验证规则并让您的 VM 实施 IDataErrorInfo and INotifyDataErrorInfo。
考虑一下——除非您的 VM 中的数据有效,否则您的保存命令不应执行。这意味着验证逻辑应该在您的 VM 中,而不是在您的 UI.
中实现这些接口使得检查您是否execute/can 执行并在 CanExecute 更改时触发适当的事件变得微不足道。