简体   繁体   中英

SelectionChanged Event fires before Selection is made

So I'm trying to change the border color of a ComboBox AFTER the user has chosen an Item. (From Red to Green/Gray/AnyOtherColor)

Problem: Wenn I run the code, the event seems to fire BEFORE the user has made a selection.

My ComboBox is within multiple Grids and is Styled with a ResourceDictionary (I'm going to show the code in a sec).

I attatched a SelectionChanged Event in my lack of better knowledge.

XAML ComboBox:

<ComboBox Grid.Column="1"
                  Grid.Row="1"
                  Style="{StaticResource FormComboBox}" 
                  x:Name="comboAnrede"
                  SelectionChanged="ComboBox_SelectionChanged" >
            <ComboBoxItem Content="Keine Angabe"
                          IsSelected="True"/>
            <ComboBoxItem Content="Dr." />
            <ComboBoxItem Content="Prof." />
            <ComboBoxItem Content="Prof. Dr." />
            <ComboBoxItem Content="Mag." />
            <ComboBoxItem Content="Ing." />
            <ComboBoxItem Content="Ba." />
        </ComboBox>

Code Behind

 private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        comboAnrede.BorderBrush = new SolidColorBrush(new Color { R = 204, G = 204, B = 204, A = byte.MaxValue });
    }

Resource Dictionary

<Style TargetType="ComboBox" x:Key="FormComboBox">
    <Setter Property="Margin" Value="10,0" />
    <Setter Property="HorizontalAlignment" Value="Stretch" />
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="BorderBrush" Value="Red" />
    <Setter Property="BorderThickness" Value="0,0,0,1" />
</Style>

Does anyone know how I can make it wait for the actual selection? (Also if possible could you try to explain to me if and when how I can reuse the very same event for other ComboBoxes?)

When the combobox loads initially, no item is selected. It then sets the selected item to "Keine Angabe" based on the IsSelected property. This then causes the selection change event to fire. If you remove it, you will see the event is not fired.

You can re-use the method for other comboboxes by casting the sender to the combobox type: See below:

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var combobox = sender as ComboBox;
            combobox.BorderBrush = new SolidColorBrush(new Color { R = 204, G = 204, B = 204, A = byte.MaxValue });
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM