[英]Bind ComboBox Source with ViewModel (mvvm wpf)
this is my Code (my ViewModel: 这是我的代码(我的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; }
}
I am reading a whole Column from my DataBase and i am storing it in "empList". 我正在从数据库中读取整个列,并将其存储在“ empList”中。 Atleast thats what i think im doing.
我认为我正在做的是Atleast。
I have a Combobox and want to bind the Source to Countries in XAML: 我有一个组合框,想要将源绑定到XAML中的国家 :
ItemsSource="{Binding Countries}"
but i dont get the names of the Countries and i dont know what im doing wrong 但是我没有得到国家的名字,我也不知道我做错了什么
please help:( 请帮忙:(
thanks in advance 提前致谢
I think this is what you're trying to accomplish. 我认为这就是您要完成的工作。
First your combobox should looks something like this. 首先,您的组合框应该看起来像这样。
<ComboBox DisplayMemberPath="Name" ItemsSource="{Binding Countries}"></ComboBox>
Model may look like this: 模型可能如下所示:
public class Country
{
public string Name { get; set; }
}
Then your viewModel should look something like: 然后,您的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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.