有幾種方法可以實現你想要的。這裏有一對夫婦。選擇適合你的。
1.使用值轉換器
設置您的組合框是這樣的:
<ComboBox
ItemsSource="{Binding Genders}"
SelectedItem="{Binding Gender, Converter={x:Static local:GenderConverter.Instance}}" />
在視圖模型:
// Hook up to your data however you want
public int Gender
{
get { return _gender; }
set
{
if (_gender != value)
{
_gender = value;
OnPropertyChanged();
}
}
}
private int _gender;
// Initialize to ["Male", "Female"]
public string[] Genders { get; private set; }
和轉換器:
internal class GenderConverter : IValueConverter
{
public static GenderConverter Instance { get; private set; }
static GenderConverter()
{
Instance = new GenderConverter();
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is int)
{
switch ((int)value)
{
case 1: return "Male";
case 2: return "Female";
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string)
{
string gender = (string)value;
if (string.Compare(gender, "Male", true) == 0) return 1;
if (string.Compare(gender, "Female", true) == 0) return 2;
}
return null;
}
}
2.轉換成視圖模型
值設置您的組合框是這樣的:
<ComboBox
ItemsSource="{Binding Genders}"
SelectedItem="{Binding Gender}" />
在視圖模型:
// Hook up to your data however you want
public string Gender
{
get
{
switch(_gender)
{
case 1: return "Male";
case 2: return "Female";
default: return null;
}
}
set
{
int actualValue = 0;
if (string.Compare(value, "Male", true) == 0) actualValue = 1;
if (string.Compare(value, "Female", true) == 0) actualValue = 2;
if (_gender != actualValue)
{
_gender = actualValue;
OnPropertyChanged();
}
}
}
private int _gender;
// Initialize to ["Male", "Female"]
public string[] Genders { get; private set; }
啊呀。如果我在數據庫中有一個單獨的表,我可以項目源結合更加容易'<組合框的ItemsSource =「{結合的RelativeSource = {的RelativeSource模式= FindAncestor,AncestorType = {X:類型的StackPanel}},路徑= DataContext.GendersTable }「DisplayMemberPath =」Gender「SelectedValuePath =」ID「SelectedValue =」{Binding GenderID}「/>'。它只是使我的數據庫與2行2列的表,將永遠不會改變... –