Search code examples
c#wpfmvvmcomboboxviewmodel

Make ComboBox Border red if item is not yet selected


I’m new to C# and WPFs, and honestly just started learning on my own this week. I’m trying to make a drop down menu that highlights red (signaling that this field is required) until an item is selected. I don’t have an item on the list that’s empty per se, but the default state is a blank option. Once one item is selected, you cannot reach the blank option again.

I’ve tried a bunch of different approaches, and believe that I am at the understanding that I need to make a style template that requests validation in order to change the border color. However, I’m encountering some issues with that. It never really sees a validation error when running. I think I must just have a fundamental misunderstanding of how to use validations (basically the syntax requirements of making my own validation and using it for this trigger).

If there is any way to accomplish this without validations that might be easier for me, but I didn’t see anything online describing that. Any help would be appreciated.

My XAML ComboBox template style:

 <Style x:Key="ComboBoxValidationStyle" TargetType="ComboBox">
     <Setter Property="Template">
         <Setter.Value>
             <ControlTemplate TargetType="ComboBox">
                 <Border x:Name="border" BorderBrush="Green" BorderThickness="1">
                     <ComboBox x:Name="PART_EditableTextBox"
                               ItemsSource="{TemplateBinding ItemsSource}" 
                               SelectedItem="{Binding SelectedModelNumber, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}">
                     </ComboBox>
                 </Border>
                 <ControlTemplate.Triggers>
                     <Trigger Property="Validation.HasError" Value="True">
                         <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
                         <Setter Property="BorderBrush" TargetName="border" Value="Red"/>
                         <Setter Property="BorderThickness" TargetName="border" Value="1"/>
                     </Trigger>
                     <Trigger Property="IsMouseOver" Value="True">
                         <Setter Property="BorderBrush" TargetName="border" Value="#00aed7"/>
                     </Trigger>
                 </ControlTemplate.Triggers>
             </ControlTemplate>
         </Setter.Value>
     </Setter>
 </Style>

MY XAML ComboBox Code:

           <ComboBox Grid.Row="1" FontSize="15" Grid.Column="2" Width="110" Height="27" Margin="26,0,0,0" Style="{StaticResource ComboBoxValidationStyle}" ItemsSource="{Binding ModelNumbers}" Name="comboBox1">
               <ComboBox.SelectedItem>
                   <Binding Path="Name" Mode="TwoWay" RelativeSource="{RelativeSource Mode=TemplatedParent}" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True">
                       <Binding.ValidationRules>
                           <local:SelectionValidationRule></local:SelectionValidationRule>
                       </Binding.ValidationRules>
                   </Binding>
               </ComboBox.SelectedItem>
           </ComboBox>

My Validation code:

    public class SelectionValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value is string selectedItemString)
            {
                if (string.IsNullOrEmpty(selectedItemString))
                {
                    return new ValidationResult(false, null);
                }
            }
            else if (value == null || string.IsNullOrEmpty(value.ToString()))
            {
                return new ValidationResult(false, null);
            }
            else if (value is ComboBox comboBox)
            {
                if (comboBox.SelectedIndex == -1)
                {
                    return new ValidationResult(false, null);
                }
            }

            return new ValidationResult(true, null);
        }
    }

And yes, I did include the SelectionValidationRule class in my XAML code behind!


Solution

  • DataTriggers allow you to change style properties according to values of other properties. You can have the Border color automatically change according to the value of the ComboBox's SelectedIndex, which starts at 0 at the first selectable item and is -1 if no selection is made, which I assume is what you want to prevent.

    Change your Border tag to:

                <Border x:Name="border" BorderThickness="1">
                  <Border.Resources>
                    <Style TargetType="Border">
                      <Setter Property="BorderBrush" Value="Green"/>
                      <Style.Triggers>
                        <DataTrigger Binding="{Binding SelectedIndex, ElementName=PART_EditableTextBox}" Value="-1">
                          <Setter Property="BorderBrush" Value="Red"/>
                        </DataTrigger>
                      </Style.Triggers>
                    </Style>
                  </Border.Resources>
                  <ComboBox x:Name="PART_EditableTextBox"
                                   ItemsSource="{TemplateBinding ItemsSource}" 
                                   SelectedItem="{Binding SelectedModelNumber, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}">
                  </ComboBox>
                </Border>
    

    And you can safely rip out the ComboBox.SelectedItem tag and SelectionValidationRule class if you don't need stricter enforcement. But the above should be all you need to change the Border color. Hope this helps...