这是我的代码(我的ViewModel:
NamesDB.Open();
string NamesCommand = "SELECT * FROM [Country]";
OleDbDataAdapter dr = new OleDbDataAdapter(new OleDbCommand(NamesCommand, NamesDB));
DataSet ds = new DataSet();
dr.Fill(ds);
var empList = ds.Tables[0].AsEnumerable().Select(dataRow => new Country { Name = dataRow.Field<string>("NameCountry")}).ToList();
Countries = empList;
NamesDB.Close();
public List<Country> Countries { get; set; }
public class Country
{
public string Name { get; set; }
}
我正在从数据库中读取整个列,并将其存储在“ empList”中。我想我就是这么做的。
我有一个组合框,想要将源绑定到XAML中的国家/地区:
ItemsSource="{Binding Countries}"
但是我没有得到国家的名字,我也不知道我做错了什么
请帮助:(
预先感谢
答案 0 :(得分:0)
我认为这就是您要完成的工作。
首先,您的组合框应该看起来像这样。
<ComboBox DisplayMemberPath="Name" ItemsSource="{Binding Countries}"></ComboBox>
模型可能看起来像这样:
public class Country
{
public string Name { get; set; }
}
然后,您的viewModel应该类似于:
public class MainWindowViewModel : INotifyPropertyChanged
{
public MainWindowViewModel()
{
GetData();
}
private List<Country> _countries;
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public List<Country> Countries
{
get => _countries;
set
{
_countries = value;
OnPropertyChanged();
}
}
private void GetData()
{
// call database here
var countries = new List<Country>()
{
new Country() {Name = "Usa"},
new Country() {Name = "Mexico"},
};
Countries = countries;
}
}public class MainWindowViewModel : INotifyPropertyChanged
{
public MainWindowViewModel()
{
GetData();
}
private List<Country> _countries;
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public List<Country> Countries
{
get => _countries;
set
{
_countries = value;
OnPropertyChanged();
}
}
private void GetData()
{
// call database here
var countries = new List<Country>()
{
new Country() {Name = "Usa"},
new Country() {Name = "Mexico"},
};
Countries = countries;
}
}