Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear combobox in WPF

I have a Combobox that I would like to clear whenever a checkbox is checked. How would I go about doing that?

My combobox:

<ComboBox
   DisplayMemberPath="KommuneNavn"
   SelectedValuePath="KommuneNr"
   ItemsSource="{Binding KommuneNavne}"
   SelectedValue="{Binding kommuneNr, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
   Margin="3"
   IsEnabled="{Binding IsUdenlandskAdresse, Converter={StaticResource BooleanNotConverter}}"/>

My Checkbox that binds to a boolean property IsUdenlandskAdresse in my viewmodel:

<CheckBox Margin="3" IsChecked="{Binding IsUdenlandskAdresse, Mode=TwoWay}"/>

So when IsUdenlandskadresse is set to true, I would like the combobox to become blank.

like image 596
Boris Grunwald Avatar asked Jan 28 '26 10:01

Boris Grunwald


1 Answers

If I understood what you are trying to do correctly, you want the ComoBox to be blank (or at least look blank) when it is disabled. The simplest way to do this is to change the Foreground (The color used for Text) to Transparent when the ComboBox is disabled with a style. That way you won't need any code-behind, can reuse that behavior on other ComboBoxes and you don't lose the selection if it gets re-enabled.

<Style TargetType="ComboBox">
    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Foreground" Value="Transparent"/>
        </Trigger>
    </Style.Triggers>
</Style>

Minimalistic Demo:

enter image description here

<ComboBox Height="Auto" IsEnabled="{Binding ElementName=cckEnabled, Path=IsChecked}">
    <ComboBox.Style>
        <Style TargetType="ComboBox">
            <Style.Triggers>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Foreground" Value="Transparent"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
    <ComboBoxItem>Entry 1</ComboBoxItem>
    <ComboBoxItem>Entry 2</ComboBoxItem>
    <ComboBoxItem>Entry 3</ComboBoxItem>
    <ComboBoxItem>Entry 4</ComboBoxItem>
    <ComboBoxItem>Entry 5</ComboBoxItem>
</ComboBox>
<CheckBox Name="cckEnabled" Content="Enabled"/>
like image 69
Manfred Radlwimmer Avatar answered Jan 30 '26 03:01

Manfred Radlwimmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!