Andrew
Andrew

Reputation: 986

How to select ComboBox item depending on the value of binding variable?

I would like to ask, how to select Combobox item depeding on the value of the binding variable. For example bind boolean variable sex to bind value true to male and false to female?

<ComboBox>
    <ComboBoxItem Content="male"/>        <- select if true
    <ComboBoxItem Content="female" />     <- select if false
</ComboBox>

Upvotes: 0

Views: 599

Answers (1)

Anatoliy Nikolaev
Anatoliy Nikolaev

Reputation: 22702

Try this example:

<RadioButton Name="Female"
             Content="Female" 
             Margin="0,0,0,0" />

<RadioButton Name="Male"
             Content="Male"
             Margin="0,20,0,0" />

<ComboBox Width="100" Height="25">
    <ComboBoxItem Content="Male" 
                  IsSelected="{Binding Path=IsChecked, 
                                       ElementName=Male}" />           

    <ComboBoxItem Content="Female"
                  IsSelected="{Binding Path=IsChecked, 
                                       ElementName=Female}" />                
</ComboBox>

As more universal solution you can use Converter:

Provides a way to apply custom logic to a binding.

Example:

XAML

<Window x:Class="MyNamespace.MainWindow"
        xmlns:this="clr-namespace:MyNamespace"

    <Window.Resources>
        <this:MaleFemaleConverter x:Key="MaleFemaleConverter" />
    </Window.Resources>

    <ComboBox Width="100" 
              Height="25"
              SelectedIndex="{Binding Path=IsChecked, <--- Here can be your variable
                                      ElementName=SomeElement, 
                                      Converter={StaticResource MaleFemaleConverter}}">

        <ComboBoxItem Content="Male" />
        <ComboBoxItem Content="Female" />                
    </ComboBox>     

Code-behind

public class MaleFemaleConverter : IValueConverter    
{        
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)        
    {            
        bool Value = (bool)value;

        if (Value == true) 
        {
            return 1;
        }

        return 0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return DependencyProperty.UnsetValue; 
    }            
}

Upvotes: 1

Related Questions