如何防止WPF Combobox为空

7

我有一个WPF组合框,它绑定了一些内容。用户必须选择其中一个项目。如果他们没有选择任何内容,我想发出警告并让用户重新选择。

如何实现这个功能?

我考虑添加一个“选择”按钮。当用户没有选择任何内容时,我会设置:

if (combobox.SelectedItem == null)
{
    MessageBox.Show("Please select one");

    //Here is the code to go back to selection
}

是否有一种通用的解决方案来满足这个需求?

提前感谢。


2
不要仅仅发出警告,而是在第一时间阻止他们这样做。如果您有一个用于处理数据的按钮,则在未选择任何内容时禁用该按钮。 - paparazzo
让用户无法选择空值。填充下拉框并设置:combobox.SelectedIndex = 0; - Max
嗨Blam,我该怎么做? - Chelseajcole
嗨Mobstaa,如果我这样做,也就是说如果用户没有从下拉列表中选择任何内容,它会自动为他们选择第一个元素。对吧? - Chelseajcole
2个回答

10

你可以在 ComboBoxSelectedItem 上创建一个 ValidationRule,这样你就可以让用户界面告诉用户他们需要做些什么。

例子:

验证规则:

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.

enter image description here

当然它是WPF,因此您可以自定义一切,因此您可以添加一个失败的ValidationControlTemplate并将验证消息作为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>

结果:

enter image description here


1

您可以用多种方法实现这一点,但其中一种方法可能是:

  • 使用转换器将“选择”按钮的IsEnabled属性绑定到组合框的SelectedItem上,如果SelectedItem不为空,则输出True,否则输出False
  • 也许还可以在组合框中定义一个触发器,在SelectedItem为空时显示警告(使用相同类型的转换器来设置触发器)

您可以像这样实现类型转换器:

[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;
    }
 }

然后,您可以像这样使用它:
 <local:NullToBoolConverter x:Key="nullToBoolConverter"/>

 <Button IsEnabled="{Binding ElementName=nameOfCombobox, Path=SelectedItem, Converter={StaticResource nullToBoolConverter}}" Content="Select"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接