7

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.

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.

4

2 に答える 2

10

を作成して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これにより、赤で輪郭が描かれます

ここに画像の説明を入力

そしてもちろんWPF、すべてをカスタマイズできるので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>

結果:

ここに画像の説明を入力

于 2013-03-11T21:33:07.777 に答える
1

複数の方法でそれを達成できますが、1 つのアプローチとして次のようなものがあります。

  • SelectedItem が null でない場合は True を出力し、それ以外の場合は False を出力するコンバーターを使用して、「選択」ボタンの IsEnabled プロパティをコンボボックスの SelectedItem にバインドします。
  • また、SelectedItem が null の場合に警告を表示するように、コンボ ボックスでトリガーを定義することもできます (同じ型コンバーターを使用してトリガーを設定します)。

次のように型コンバーターを実装できます。

[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"/>
于 2013-03-11T15:22:39.873 に答える