[英]Suppress ListView selection changed when clearing items from the observable collection
[英]Finding the items changed in Observable Collection
我有一個來自EF db上下文的類,該類已在基於ObservableCollection的數據網格中顯示。 用戶可以編輯網格,並且所有這些都可以正常顯示。
但是,現在我需要將數據發送回數據庫。 我不想將集合中的所有項目發送到我的保存方法,因此我只能找到集合中發生更改的項目嗎?
就像一個想法(並不是說這是一個理想的解決方案)一樣,我遇到了類似的問題,四處尋找潛在的解決方案,但這些都不是我想要的。
我不得不將一個集合傳遞給WPF DataGrid,它似乎抱怨使用List,因此我轉向了ObservableCollection
由於多種原因,我不想直接使用EF上下文,主要是因為我想獲取項目並將其傳遞給要處理的中間事務工廠(業務邏輯)。
因此決定堅持使用ObservableCollection,而對ViewModel進行一些修改,因為我可以自由地這樣做。
我的模型最終看起來像這樣:
internal class databaseItemModel
{
int _id;
string _description;
decimal _price;
decimal _quantity;
decimal _cost;
bool _modified;
public databaseItemModel()
{
_modified = false;
}
public int id { get { return _id; } }
public bool modified { get { return _modified; } }
public string description { get { return _description; } set { _description = value; _modified = true; } }
public decimal price { get { return _price; } set { _price = value; _modified = true; } }
public decimal quantity { get { return _quantity; } set { _quantity = value; _modified = true; } }
public decimal cost { get { return _cost; } set { _cost = value; _modified = true; } }
public bool selected { get; set; }
public void setId(int _idvalue)
{
_id = _idvalue;
}
public decimal value
{
get { return price * quantity; }
}
public void setDescription(string _descr)
{
_description = _descr;
}
public void setPrice(decimal _pr)
{
_price = _pr;
}
public void setQuantity(decimal _qty)
{
_quantity = _qty;
}
public void setCost(decimal _cst)
{
_cost = _cst;
}
}
基本上,它背后的簡單想法是,我將使用函數來填充數據,而不是直接使用屬性,然后將該項目傳遞給ObservableCollection,后者隨后將成為DataGrid.ItemsSource的源。
由於DataGrid / ObservableCollection將與屬性一起使用-修改后的對象將被標記為已修改,然后我將能夠在退出時提取集合並收集修改后的項。
希望這會有所幫助。
您可以使用NotifyCollectionChangedAction
來檢測ObservableCollection
已更改的項目
但是,僅Jens
所說,最好的方法就是讓EF為您處理。
干杯。
ObservableCollection<int> listOfObject = new ObservableCollection<int>() { 1, 2, 3, 4};
listOfObject.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(
delegate (object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
Console.WriteLine($"{e.NewItems[0]} just been added to the list at index = {e.NewStartingIndex}");
}
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Replace)
{
Console.WriteLine($"Replace item {e.OldItems[0]} with {e.NewItems[0]}");
}
}
);
listOfObject.Add(1);
listOfObject[2] = 3;
listOfObject[3] = 1;
輸出:
1剛剛被添加到索引= 4的列表中
將項目3替換為3
將項目4替換為1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.