如何根据绑定变量的值选择ComboBox项目?

安德鲁

我想问一下如何根据绑定变量的值选择Combobox项目。例如,将boolean变量sex绑定true将value绑定male,将false绑定female

<ComboBox>
    <ComboBoxItem Content="male"/>        <- select if true
    <ComboBoxItem Content="female" />     <- select if false
</ComboBox>
阿纳托利·尼古拉耶夫(Anatoliy Nikolaev)

试试这个例子:

<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>

作为更通用的解决方案,您可以使用Converter

提供一种将自定义逻辑应用于绑定的方法。

例子:

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; 
    }            
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章