我想問一下,如何根據綁定變量的值選擇Combobox項目。例如綁定布爾變量性別綁定值真到男性和假到女?如何根據綁定變量的值選擇ComboBox項目?
<ComboBox>
<ComboBoxItem Content="male"/> <- select if true
<ComboBoxItem Content="female" /> <- select if false
</ComboBox>
我想問一下,如何根據綁定變量的值選擇Combobox項目。例如綁定布爾變量性別綁定值真到男性和假到女?如何根據綁定變量的值選擇ComboBox項目?
<ComboBox>
<ComboBoxItem Content="male"/> <- select if true
<ComboBoxItem Content="female" /> <- select if false
</ComboBox>
試試這個例子:
<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;
}
}
如果我的價值是真實的,那麼我想與內容MALE到selest項目。並且當它是假的時候,我想選擇帶有內容FEMALE的項目。 – Andrew