正如问题所说,我被困在用我的内容填充数据容器(listview)上,希望有人能告诉我一个亮点!
这是我拥有的类(我的搜索框发送一个我想在数据库上找到的参数名称,对我的数据库的查询填充并检索一个 ObservableCollection,其中填充了尽可能多的参数,然后我想把它展示到我的列表视图,希望有人可以帮助我!提前感谢!
public class LobbyUserViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private DbOperations.DbOperations db;
private ObservableCollection<Person> persons;
public LobbyUserViewModel()
{
persons = new ObservableCollection<Person>();
db = new DbOperations.DbOperations();
searchPersonCommand = new RelayCommand(SearchPerson, CanSearchPerson);
}
public ICommand SearchPersonCommand
{
get { return searchPersonCommand; }
}
public bool CanSearchPerson(object obj)
{
if (SearchPersonBox != string.Empty)
return true;
return false;
}
public void SearchPerson(object obj)
{
Persons = db.DadosForSearchPerson(searchPerson);
if (Persons != null)
{
foreach (var item in Persons)
{
MessageBox.Show(item.Name + " - " + item.Email);
// This works, but I need these 2 items added on a listview
}
}
else
{
MessageBox.Show("Noone found with that name");
}
}
public string SearchPersonBox
{
get { return searchPerson.Name; }
set
{
searchPerson.Name = value;
OnPropertyChanged("SearchPerson");
}
}
public ObservableCollection<Person> Persons
{
get { return persons; }
set { persons = value; }
}
你需要在你的Persons
二传手中提高属性更改。目前,每次调用SearchPerson()
时都会替换ObservableCollection
,但由于您不提高PropertyChanged
,WPF无法知道它已更改。
由于每次都替换集合,因此仅改用List<T>
可能会更有效。 仅当您要动态添加/删除/移动现有集合中的项目时,才需要ObservableCollection<T>
。
+1 代表 GazTheDestroyer。 没有OnPropertyChanged的解决方案是这样的:
public void SearchPerson(object obj)
{
if(!CanSearchPerson(obj))
return;
Persons.Clear();
var result = db.DadosForSearchPerson(searchPerson);
if (result != null)
{
foreach (var item in result )
{
MessageBox.Show(item.Name + " - " + item.Email);
// This works, but I need these 2 items added on a listview
Persons.Add(item)
}
}
else
{
MessageBox.Show("Noone found with that name");
}
}
你的 Xaml
<ListView ItemsSource="{Binding Persons}">
<ListView.View>
<GridView>
<GridViewColumn Width="140" Header="Name" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Width="140" Header="Email" DisplayMemberBinding="{Binding Email}" />
</GridView>
</ListView.View>
</ListView>