如何在WPF c#中使用数据绑定?



我想在wpf中将我的控件与我的视图模型绑定,并在数据库更新时自动更新数据控件。我实现了一个视图模型,它有一些List<myClass>属性,并从数据库接收数据,这些数据将保存在这些属性中。然后将控件源代码绑定到这些属性。这是好的,但当我从数据库获得新的数据,并将其保存在这些属性,控件数据不更新。我如何通过编程来修复它?

这是我的代码:

public partial class MainWindow : Window
{
ListOfPerson personList1 = new ListOfPerson();
ListOfPerson personList2 = new ListOfPerson();

public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
personList1.People.Add(new Person { PersonName = "test1" });
personList2.People.Add(new Person { PersonName = "test2" });
dg.AutoGenerateColumns = false;
PropertyPath prop = new PropertyPath("PersonName");
Binding bind = new Binding();
bind.Mode = BindingMode.TwoWay;
bind.Path = prop;
dg.Columns.Add(new DataGridTextColumn { Header = "Name", Binding = bind });
dg.ItemsSource = personList1.People;
}
public void Refresh()
{
personList1.People = personList2.People;
}
private void btn_Refresh_Click(object sender, RoutedEventArgs e)
{
Refresh();
}
}
public class Person : INotifyPropertyChanged
{
private string name;
public Person()
{
}
public Person(string value)
{
this.name = value;
}
public string PersonName
{
get { return name; }
set
{
name = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
public class ListOfPerson : INotifyPropertyChanged
{
private List<Person> people = new List<Person>();
public List<Person> People
{
get
{
return people;
}
set
{
people = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}

您直接分配您的ItemsSource,即而不是绑定.

dg.ItemsSource = personList1.People;

然而,在Refresh上,您替换personList1People集合。

personList1.People = personList2.People;

items源仍然有对旧集合的引用,因为您直接分配了它。您可以添加一个绑定,它会注意到项目源通过ListOfPerson中的People属性的属性更改通知实现而更改。这应该可以工作:

Binding itemsSourceBinding = new Binding
{
Source = personList1,
Path = new PropertyPath("People")
};
BindingOperations.SetBinding(dg, DataGrid.ItemsSourceProperty, itemsSourceBinding);

这只是处理此场景的一个选项。另一个选择是只使用单个ObservableCollection<T>,您Clear和填充再次或修改之间(如果您将其替换为新实例)与代码中的列表一样,您会遇到与上面相同的问题)。它实现了INotifyCollectionChanged接口并通知更改,如自动添加,删除或插入项,从而更新UI。

相关内容

  • 没有找到相关文章

最新更新