您可以创建一个ValidationRule
然后ComboBox
SelectedItem,
您可以让 UI 向用户显示他们需要做某事。
例子:
验证规则:
public class SelectionValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
return value == null
? new ValidationResult(false, "Please select one")
: new ValidationResult(true, null);
}
}
组合框:
<ComboBox ItemsSource="{Binding Items}" >
<ComboBox.SelectedItem>
<Binding Path="SelectedItem">
<Binding.ValidationRules>
<local:SelectionValidationRule ValidatesOnTargetUpdated="True"/>
</Binding.ValidationRules>
</Binding>
</ComboBox.SelectedItem>
</ComboBox>
这将勾勒出ComboBox
红色
当然还有 ite WPF
,因此您可以自定义所有内容,因此您可以ControlTemplate
为失败添加 aValidation
并将验证消息添加为ToolTip
.
<Window x:Class="WpfApplication9.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication9"
Title="MainWindow" Height="132" Width="278" Name="UI">
<Window.Resources>
<!--If there is a validation error, show in tooltip-->
<Style TargetType="ComboBox" >
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
<!--Create a template to show if validation fails-->
<ControlTemplate x:Key="ErrorTemplate">
<DockPanel>
<Border BorderBrush="Red" BorderThickness="1" >
<AdornedElementPlaceholder/>
</Border>
<TextBlock Foreground="Red" FontSize="20" Text=" ! " />
</DockPanel>
</ControlTemplate>
</Window.Resources>
<Grid DataContext="{Binding ElementName=UI}">
<ComboBox ItemsSource="{Binding Items}" Margin="21,20,22,48" Validation.ErrorTemplate="{StaticResource ErrorTemplate}">
<ComboBox.SelectedItem>
<Binding Path="SelectedItem">
<Binding.ValidationRules>
<local:SelectionValidationRule ValidatesOnTargetUpdated="True"/>
</Binding.ValidationRules>
</Binding>
</ComboBox.SelectedItem>
</ComboBox>
</Grid>
</Window>
结果: