I have a problem binding List to a DataGrid element. I've created a class that implements INotifyPropertyChange and keeps list of orders:
public class Order : INotifyPropertyChanged
{
private String customerName;
public String CustomerName
{
get { return customerName; }
set {
customerName = value;
NotifyPropertyChanged("CustomerName");
}
}
private List<String> orderList = new List<string>();
public List<String> OrderList
{
get { return orderList; }
set {
orderList = value;
NotifyPropertyChanged("OrderList");
}
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
In xaml a have a simple DataGrid component that Binds the OrderList e开发者_StackOverflow中文版lement:
<data:DataGrid x:Name="OrderList" ItemsSource="{**Binding OrderList**, Mode=TwoWay}" Height="500" Width="250" Margin="0,0,0,0" VerticalAlignment="Center"
I also have a button in GUI taht adds a element to OrderList:
order.OrderList.Add("item");
The DataContext is set to the global object:
Order order = new Order();
OrderList.DataContext = order;
The problem is that when i Click the button, the item does not apear in dataGrid. It apears after a click on a grid row. It seams like INotifyPropertyChange does not work... What am I doing wrong??
Please HELP:)
INotifyPropertyChange is working fine, since your code to Add a new item to the existing List
does not actually re-assign a new value to the OrderList
property (that is the set
routine is never called) there is no call to NotifyPropertyChanged
. Try it like this:-
public class Order : INotifyPropertyChanged
{
private String customerName;
public String CustomerName
{
get { return customerName; }
set {
customerName = value;
NotifyPropertyChanged("CustomerName");
}
}
private ObservableCollection<String> orderList = new ObservableCollection<String>();
public ObservableCollection<String> OrderList
{
get { return orderList; }
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
The ObservableCollection<T>
type supports informing INotifyCollectionChanged
which will inform the DataGrid
when items are added to or removed from the collection.
精彩评论