您的产品类必须实现InotifyPropertyChanged接口,并且您应该在每次更改时更新可绑定属性以引发此事件。这就是绑定在WPF中的工作方式。
像这样的片段
public class Produts : INotifyPropertyChanged
{
public Produts()
{
}
int productID;
public int ProductID
{
get { return productID; }
set
{
if (productID != value)
{
productID = value;
OnPropertyChange("ProductID");
}
}
}
int quantity;
public int Quantity
{
get { return quantity; }
set
{
quantity = value;
OnPropertyChange("Quantity");
//Force Subtotal to be updated
OnPropertyChange("SubTotal");
}
}
string description;
public string Description
{
get { return description; }
set
{
description = value;
OnPropertyChange("Description");
}
}
decimal price;
public decimal Price
{
get { return price; }
set
{
price = value;
OnPropertyChange("Price");
//Force Subtotal to be updated
OnPropertyChange("SubTotal");
}
}
public decimal SubTotal
{
get { return Quantity * Price; }
}
public static List<Produts> ProductList
{
get
{
return new List<Produts>();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChange(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
这里是XAML:
<DataGrid ItemsSource="{Binding Path=ProductList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding Path= ProductID}"/>
<DataGridTextColumn Header="Quantity" Binding="{Binding Path=Quantity}"/>
<DataGridTextColumn Header="Description" Binding="{Binding Path=Description}"/>
<DataGridTextColumn Header="Price" Binding="{Binding Path=Price}"/>
<DataGridTextColumn Header="Subtotal" Binding="{Binding Path=SubTotal, Mode=OneWay}"/>
</DataGrid.Columns>
</DataGrid>
这一行在window的构造器中
base.DataContext = new Produts();