我想问一下,如何根据绑定变量的值选择Combobox项。例如,绑定布尔变量sex将值 true 绑定到 male ,将 false 绑定到 female ?
<ComboBox>
<ComboBoxItem Content="male"/> <- select if true
<ComboBoxItem Content="female" /> <- select if false
</ComboBox>
答案 0 :(得分:1)
试试这个例子:
<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;
}
}