我正在學習WPF,所以請裸露我的問題,如果它是非常新手!我有一個Items集合,我想將該集合綁定到一個Grid並將Sum綁定到一個文本框。在線搜索我發現這個類將會引發事件,即使我們對集合對象的屬性進行了更改。如何綁定WPF中Observable集合的總和
ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)
但我似乎不能讓它在我的代碼工作。
這裏是我的代碼
SaleItem
public class SaleItem : INotifyPropertyChanged
{
public int Num { get; set; }
public string ItemID { get; set; }
public string Name { get; set; }
private decimal price;
public decimal Price
{
get { return price; }
set
{
this.price = value;
OnPropertyChanged("Total");
}
}
public int quantity;
public int Quantity
{
get { return quantity; }
set
{
this.quantity = value;
OnPropertyChanged("Total");
}
}
public decimal Total
{
get { return decimal.Round(Price * Quantity, 2, MidpointRounding.AwayFromZero);}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
售
public class Sale : INotifyPropertyChanged
{
private Decimal _total;
public TrulyObservableCollection<SaleItem> Items { get; set; }
public Sale()
{
Items = new TrulyObservableCollection<SaleItem>();
Items.Add(new SaleItem { ItemID = "1", Name = "Product 1", Price = 10, Quantity = 1 });
Items.Add(new SaleItem { ItemID = "2", Name = "Product 2", Price = 10, Quantity = 1 });
Items.Add(new SaleItem { ItemID = "3", Name = "Product 3", Price = 10, Quantity = 1 });
}
public Decimal Total
{
get
{
return Items.Sum(x => x.Total);
}
set
{
_total = value;
OnPropertyChanged("Total");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
主窗口
public partial class MainWindow : Window
{
public Sale Model { get; set; }
public MainWindow()
{
InitializeComponent();
Model = new Sale();
this.DataContext = Model;
}
private void btnQuantity_Click(object sender, RoutedEventArgs e)
{
Model.Items.Add(new SaleItem { ItemID = "2", Name = "Product 2", Price = 10, Quantity = 1 });
}
}
XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:Sale />
</Window.DataContext>
<Grid>
<StackPanel>
<DataGrid x:Name="grdItems" ItemsSource="{Binding Items}"></DataGrid>
<TextBlock x:Name="txtTotal" Text="{Binding Total}"/>
<Button x:Name="btnQuantity" Content="Update" Click="btnQuantity_Click"/>
</StackPanel>
</Grid>
我想測試增加一個項目,當我按一下按鈕,並更新項目的網格數量。如果我設置了一個斷點並查看Total的值,那麼它是正確的,但不知何故它不會在UI上更新。我在這裏錯過了什麼?
短而甜!謝謝! –
我應該解開事件的地方?或者讓GC完成這項工作? –