我怎么能不允许 WPF 组合框为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15342143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I not allow WPF Combobox empty
提问by Chelseajcole
I have a WPF combobox that is I bound to some stuff. Users have to select one of the items. If they don't select anything, I would like to give a warning and let the user re-select.
我有一个 WPF 组合框,我绑定了一些东西。用户必须选择其中一项。如果他们不选择任何内容,我想发出警告并让用户重新选择。
How can do that?
怎么能这样?
I am considering to have a "Select" button. When the user doesn't select anything, I set:
我正在考虑有一个“选择”按钮。当用户没有选择任何东西时,我设置:
if (combobox.SelectedItem == null)
{
MessageBox.Show("Please select one");
//Here is the code to go back to selection
}
Is there a universal solution for this requirement?
是否有针对此要求的通用解决方案?
Thanks in advance.
提前致谢。
回答by sa_ddam213
You could create a ValidationRuleon the ComboBoxSelectedItem,then you can have the UI show the user that they need to do something.
您可以创建一个ValidationRule,ComboBoxSelectedItem,然后您可以让 UI 向用户显示他们需要做的事情。
Example:
例子:
Validation Rule:
验证规则:
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:
组合框:
<ComboBox ItemsSource="{Binding Items}" >
<ComboBox.SelectedItem>
<Binding Path="SelectedItem">
<Binding.ValidationRules>
<local:SelectionValidationRule ValidatesOnTargetUpdated="True"/>
</Binding.ValidationRules>
</Binding>
</ComboBox.SelectedItem>
</ComboBox>
This will outline the ComboBoxin red
这将勾勒出ComboBox红色


And of course ite WPFso you can customize everything, so you can add a ControlTemplatefor the failed Validationand add the validation message as a ToolTip.
当然还有 iteWPF以便您可以自定义所有内容,因此您可以ControlTemplate为失败添加一个Validation并将验证消息添加为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>
Result:
结果:


回答by Mike Dinescu
You could accomplish that in multiple ways but one approach might be:
您可以通过多种方式实现这一点,但一种方法可能是:
- bind your "Select" button's IsEnabled property to the SelectedItem of the combo-box using a converter that outputs True if the SelectedItem is not null and False otherwise
- and maybe also define a trigger in the combo box to display a warning when the SelectedItem is null (use same type converter to set trigger)
- 使用转换器将“选择”按钮的 IsEnabled 属性绑定到组合框的 SelectedItem,如果 SelectedItem 不为 null,则输出 True,否则为 False
- 并且也可能在组合框中定义一个触发器以在 SelectedItem 为空时显示警告(使用相同类型的转换器设置触发器)
You might implement the type converter like this:
您可以像这样实现类型转换器:
[ValueConversion(typeof(object), typeof(bool))]
public class NullToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value != null);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
Then, you could use it like this:
然后,您可以像这样使用它:
<local:NullToBoolConverter x:Key="nullToBoolConverter"/>
<Button IsEnabled="{Binding ElementName=nameOfCombobox, Path=SelectedItem, Converter={StaticResource nullToBoolConverter}}" Content="Select"/>

