ObservableCollection deep cloning - wpf

I've implemented deep cloning of ObservableCollection in order to reset items to It's original state in editable Datagrid, via cancel button.
For this I have two collections - one ObservableCollection to bind Datagrid to It, and cloned List to re-initialize ObservableCollection to It's original state when needed.
My code works only first time I hit a cancel button, after that my cloned List has changes in It too.
Provided code is an example (mine is a bit longer), but It's 100% same as mine:
Model, which implements ICloneable:
public class EmployeeModel : ICloneable
{
public object Clone()
{
return MemberwiseClone();
}
public string NAME
{
get { return _name; }
set
{
if (_name != value)
{
CHANGE = true;
_name = value;
}
}
}
private string _name;
public string SURNAME
{
get { return _surname; }
set
{
if (_surname != value)
{
CHANGE = true;
_surname = value;
}
}
}
private string _surname;
///<summary>Property for tracking changes in model</summary>
public bool CHANGE { get; set; }
}
Viewmodel:
public ViewModel() : Base //Implements InotifyPropertyChanged
{
public ViewModel()
{
Task.Run(()=> GetData());
}
public ObservableCollection<EmployeeModel> Employees
{
get { return _employees; }
set { _employees = value; OnPropertyChanged();}
}
private ObservableCollection<EmployeeModel> _employees;
public List<EmployeeModel> Copy_employees
{
get { return _copy_employees; }
set { _copy_employees = value; OnPropertyChanged();}
}
private List<EmployeeModel> _copy_employees;
//Fetch data from DB
private async Task Get_data()
{
//Returns new ObservableCollection of type Employee
Employees = await _procedures.Get_employees();
if (Employees != null) //Now make a deep copy of Collection
{
Copy_employees = new List<EmployeeModel>();
Copy_employees = Employees.Select(s => (EmployeeModel)s.Clone()).ToList();
}
}
//My Command for canceling changes (reseting DataGrid)
//CanExecute happens, when model is changed - tracking via CHANGE property of EmployeeModel
public void Cancel_Execute(object parameter)
{
Employees.Clear(); //Tried with re-initializing too, but same result
foreach (var item in Copy_employees)// Reset binded ObservableCollection with old items
{
Employees.Add(item);
}
//Check if copied List really hasn't got any changes
foreach (EmployeeModel item in Copy_employees)
{
Console.WriteLine("Changes are " + item.CHANGES.ToString());
}
}
}
Output of cancel command:
1.) First time I hit cancel button:
// Changes are False
Every next time:
// Changes are True
So, as I see It from Console, my copied List get's updated when ObservableColection get's updated, even if It's not binded to DataGrid.
And It updates only a property which I changed, so List reflects ObservableCollection items.
How can I keep my original items of List<Employee>, and copy those into binded ObservableCollection anytime ?

When you return values, you do not return them, but write backing item references to the editable collection.
As a result, you have the same instances in both collections.
In the simplest case, when you return them, you also need to clone.
public void Cancel_Execute(object parameter)
{
Employees.Clear(); //Tried with re-initializing too, but same result
foreach (var item in Copy_employees)// Reset binded ObservableCollection with old items
{
Employees.Add((EmployeeModel)item.Clone());
}
//Check if copied List really hasn't got any changes
foreach (EmployeeModel item in Copy_employees)
{
Console.WriteLine("Changes are " + item.CHANGES.ToString());
}
}
Not relevant to the question, but I still advise you to use a slightly more user-friendly interface for cloneable:
public interface ICloneable<T> : ICloneable
{
new T Clone();
}

Related

How to use ReactiveList so UI is updated when items are added/removed/modified

I'm creating a WinForms application with a DataGridView. The DataSource is a ReactiveList. Adding new items to the list however does not update the UI.
ViewModel
public class HomeViewModel: ReactiveObject
{
public ReactiveCommand<object> AddCmd { get; private set; }
ReactiveList<Model> _models;
public ReactiveList<Model> Models
{
get { return _models; }
set { this.RaiseAndSetIfChanged(ref _models, value); }
}
public HomeViewModel()
{
Models = new ReactiveList<Model>() { new Model { Name = "John" } };
AddCmd = ReactiveCommand.Create();
AddCmd.ObserveOn(RxApp.MainThreadScheduler);
AddCmd.Subscribe( _ =>
{
Models.Add(new Model { Name = "Martha" });
});
}
}
public class Model
{
public string Name { get; set; }
}
View
public partial class HomeView : Form, IViewFor<HomeViewModel>
{
public HomeView()
{
InitializeComponent();
VM = new HomeViewModel();
this.OneWayBind(VM, x => x.Models, x => x.gvData.DataSource);
this.BindCommand(VM, x => x.AddCmd, x => x.cmdAdd);
}
public HomeViewModel VM { get; set; }
object IViewFor.ViewModel
{
get { return VM; }
set { VM = (HomeViewModel)value; }
}
HomeViewModel IViewFor<HomeViewModel>.ViewModel
{
get { return VM; }
set { VM = value; }
}
}
The view always show "John".
Debugging Subscribe show added items.
Tried it with ObservableCollection same result.How to use ReactiveList so UI is updated when new items are added
Tried it with IReactiveDerivedList same result. Does ReactiveUI RaiseAndSetIfChanged fire for List<T> Add, Delete, Modify?
I think what you want is a ReactiveBindingList rather than a ReactiveList. This is a WinForms specific version of the ReactiveList for binding purposes.
You should use BindingList.
reference :
"If you are bound to a data source that does not implement the IBindingList interface, such as an ArrayList, the bound control's data will not be updated when the data source is updated. For example, if you have a combo box bound to an ArrayList and data is added to the ArrayList, these new items will not appear in the combo box. However, you can force the combo box to be updated by calling the SuspendBinding and ResumeBinding methods on the instance of the BindingContext class to which the control is bound."
https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-bind-a-windows-forms-combobox-or-listbox-control-to-data?view=netframeworkdesktop-4.8
Or
ReactiveBindingList
It work fine for me. !!!

How to search in a lazy-loading WPF MVVM TreeView?

I need a TreeView to represent some hierarchical data from multiple tables stored in a SQL Server CE database. Before, the data was stored in xml and was simple deserialized on startup and everything was good. Now I was asked to move data to a database and I've faced a several problems.
My first problem was that it takes quite a long time to retrieve many items from DB and build a TreeView ViewModel from this items (still not sure what is longer - to get items or to construct this tree). So I implemented lazy loading and now I'm getting items only when a TreeViewItem is expanding.
Now, I need to perform a text search over all the nodes, but to make it work, all nodes must be loaded.
I tried to load all of them but the UI freezes while the tree is loading. Doing this inside a BackgroundWorker is also impossible for me because the items are stored in an ObservableCollection and I'm getting "InvalidOperationException". Using Dispatcher helps with this but it is also freezes UI...
The excerpt from my TreeViewItem VM is below, if more code is needed please let me know. Maybe I am totally wrong with my design, so any comments are very appreciated!
public class TreeViewItemViewModel: DisplayableItem, IItemsHost
{
internal static DummyTreeViewItemViewModel _dummy = new DummyTreeViewItemViewModel();
public TreeViewItemViewModel(){}
public TreeViewItemViewModel(IDisplayableItem displayableItem)
{
Data = displayableItem;
}
public TreeViewItemViewModel(IDisplayableItem displayableItem, IDisplayableItem parent)
:this(displayableItem)
{
Parent = parent as TreeViewItemViewModel;
}
private TreeViewItemViewModel _parent;
public TreeViewItemViewModel Parent
{
get { return _parent; }
set { _parent = value; InvokePropertyChanged(new PropertyChangedEventArgs("Parent")); }
}
private IDisplayableItem _data;
public new IDisplayableItem Data
{
get { return _data; }
set { _data = value; InvokePropertyChanged(new PropertyChangedEventArgs("Data")); }
}
private bool _isSelected;
public new bool IsSelected
{
get { return _isSelected; }
set { _isSelected = value; InvokePropertyChanged(new PropertyChangedEventArgs("IsSelected")); }
}
private bool _isEnabled=true;
public new bool IsEnabled
{
get { return _isEnabled; }
set { _isEnabled = value; InvokePropertyChanged(new PropertyChangedEventArgs("IsEnabled")); }
}
private bool _isVisible = true;
public new bool IsVisible
{
get { return _isVisible; }
set { _isVisible = value; InvokePropertyChanged(new PropertyChangedEventArgs("IsVisible")); }
}
private void FillItems()
{
if (Items.Contains(_dummy))
{
Items.Remove(_dummy);
var itemshost = Data as IItemsHost;
if (itemshost != null)
{
_items = new ObservableCollection<IDisplayableItem>();
foreach (var item in itemshost.Items)//getting 'Items' actually requesting them from a database
{
var treeItem = new TreeViewItemViewModel(item, this);
_items.Add(treeItem);
}
InvokePropertyChanged(new PropertyChangedEventArgs("Items"));
}
}
}
protected bool _isExpanded;
public bool IsExpanded
{
get { return _isExpanded; }
set
{
if(value)
{
FillItems();
}
_isExpanded = value;
InvokePropertyChanged(new PropertyChangedEventArgs("IsExpanded"));
}
}
protected SObservableCollection<IDisplayableItem> _items = new SObservableCollection<IDisplayableItem>();
public SObservableCollection<IDisplayableItem> Items
{
get
{
var itemshost = Data as IItemsHost;
if (itemshost != null)
{
if (_items.Count == 0 && itemshost.Items.Count > 0)
_items.Add(_dummy);
}
return _items;
}
set { _items = value; InvokePropertyChanged(new PropertyChangedEventArgs("Items")); }
}
UPDATE: for those who would search for a similar solution - my problem was in my query method. I shouldn't open a new SQL Server CE connection each time I need to perform a query...
What about a new DB table that holds a flattened representation of the entire hierarchy, and have your search logic query this table? You'll obviously need to keep this table updated as you insert/update/delete records in the other tables.
Each record in the new table would need to include some information about where the item sits in the hierarchy, so that when you get the search results back you can load and populate just those tree nodes containing the "hits".
Since reading from database is being done asynchronously so the performance bottle-neck should be constructing View from ViewModel. I suggest the following method:
Read all essential Model data from database in one async call and store them in an object called SearchHelper.
Add a a simple property (Model.Id or Model's hash code) to every ViewModel that you create in order to find the equivalent view model of an specific model.
Create only visible ViewModels. (lazy loading for ViewModel only)
Use the SearchHelper to find matches for the search query, then using the Id or hash code of the results, you can easily locate their equivalent view models.
Please Consider:
Once loaded, SearchHelper does not update itself, so you might want to manually update it.
For this method to have optimal performance, try avoiding iteration of all nodes. instead, store the sequence of traced items (their index or Id) in order to find them in view model. if each Model item knows its parent, then the back-tracking should be easy.

WinForms binding Generic List - checkable business object to a Grid

We all like how easy it is to bind with WPF. Now I am back working with Winforms and I am looking for a nice way to bind my grid to a List of Checkable of BusinessObject (I am sticking with BindingList for Winforms). So I am essentially just adding a checkable to my business object.
I am using a grid as there will be multiple columns where the user would edit (in this scenario Name and Description on the business object) - as well as adding new objects to the grid and removing from it. Checked list box does not fit for this purpose as I want to edit columns.
For this I am using .NET 4.
I basically want to reduce the amount of UI code in the scenario so I am using a view model based approach which will populate the list. I want the user to be able to check a box alongside each of the business object properties.
Sure I can use inheritance, but if I want to apply the same mechanism against a lot of business objects (having lots of different screens where you check items in a list for the different business objects). Maybe this would be the way to go - but I have my doubts.
Now depending upon the choice of grid - I am using Infragistics - the functionality would hopefully be pretty similar conceptually.
I thought about wrapping the business object up in a Checkable generic class:
using System;
using System.Collections.Generic;
public class Checkable<T> : ModelBase
{
public Checkable(T value)
{
_value = value;
}
private T _value;
public T Value
{
get
{
return _value;
}
set
{
if (!EqualityComparer<T>.Default.Equals(_value, value))
{
_value = value;
OnPropertyChanged("Value");
}
}
}
private bool _checked;
public bool Checked
{
get { return _checked; }
set
{
if (_checked != value)
{
_checked = value;
OnPropertyChanged("Checked");
}
}
}
}
I have made up a business object for this scenario:
public class BusinessObject : ModelBase
{
public BusinessObject()
{
}
public BusinessObject(RepairType repairType)
{
_name = repairType.Name;
_id = repairType.Id;
}
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
private string _description;
public string Description
{
get { return _description; }
set
{
if (description != value)
{
description = value;
OnPropertyChanged("Description");
}
}
}
private int _id;
public int Id
{
get { return _id; }
set
{
if (_id != value)
{
_id = value;
OnPropertyChanged("Id");
}
}
}
}
Where ModelBase just implements the INotifyPropertyChanged:
public abstract class ModelBase : INotifyPropertyChanged, IDisposable
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetProperty<T>(ref T field, T value, string propertyName = null)
{
if (object.Equals(field, value)) { return false; }
field = value;
OnPropertyChanged(propertyName);
return true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (disposing)
{
PropertyChanged = null;
}
}
}
So potentially for my grid datasource I would define:
// in view model
var datasource = new BindingList<Checkable<BusinessObject>>();
... populate list
grid.DataSource = viewmodel.DataSource;
So of course my scenario fails at the minute as Value is the BusinessObject reference which has the properties I want to bind to, and Checked is the property for a checkbox which I also want to bind to.
I am trying to kick start the old grey matter with some ideas on this. I don't really like writing code to define grid columns. However, the Infragistics grid has been ok for data binding directly to the BusinessObject at design time. Its possible to add an unbound column (checkbox for my scenario) and handle the checking/unchecking of items manually (which I might potentially have to do).
I am wondering if I am missing any neat tricks with Winform binding of late having missed out with Linq and Entity Framework when they appeared many years ago.

How to edit elements in a collection from another window or Dialog

I have a number of collection bound to the application main window controls shown in a
simplified form below. There are a number of other elements in the view model
(Ommited for Clarity) which all update and work as expected.
I require to edit a collection's element in another window, with the edited data back in the origonal collection.
/// Example of the Collection and Properties
ObservableCollection<MyData> _MyCollection = new ObservableCollection<MyData>();
public ObservableCollection<MyData> MyCollection { get { return _MyCollection; } }
public class MyData : INotifyPropertyChanged
{
private bool cb_checked;
public string Param1 { get; set; }
public string Param2 { get; set; }
public bool myCheck
{
get { return cb_checked; }
set
{
if (cb_checked == value) return;
cb_checked = value;
RaisePropertyChanged("Checked");
}
}
}
My problem is how do I pass an item of a collection to a new window for editing.
My intal thoughts were to pass the item in the constructor of the window
Dialog.Edit window = new Dialog.Edit(_MyCollection[2] );
window.Owner = this;
window.Show();
I also tried this as I have read I cant use indexed references
var tmp = _MyCollection[2];
Dialog.Edit window = new Dialog.Edit( tmp);
window.Owner = this;
window.Show();
but this does not work and I get null exceptions whe trying to access elements.
If I need to pass the complete collection this is also ok as they are all quite small i.e. < 50 items.
I must be going about this in the wrong way, could someone please explain how to do this
correctly please.
Many Thanks
Sarah

How do i detect a WPFDataGrid row Data changed?

I have a DataGrid,and need to detect when a user has make changes to a row.I don't want to use CellEditEnding because whenever a row get focus and lost it without any inputs,this event get raised,in the other way i need to bind a bool property to each row that set to true when the row got chgangd.
Use following code as an example, so you know the basic idea of how to trace if an item in your ItemSource had been changed (here only compared to the initial value only).
List<myItem> Items=new List<myItem>(); //your ItemSource
class myItem:ObservableObject //an class implement INotifyPropertyChanged interface
{
string _inititemName;
string _itemName;
bool itemChanged; //here is your indicator
myItem(string name)
{
_inititemName=itemName=name;
}
public string itemName
{
get{return _itemName;}
set
{
_itemName=vlaue;
if (_itemName!=_inititemName)
itemChanged=true;
else
itemChanged=false;
RaisePropertyChanged("itemName"); //or whatever the name of the method is that invoke OnPropertyChanged
}
}
}
Make the properties of your item class set a boolean update flag when they are modified
e.g.
public class MyGridItem
{
public MyGridItem(string Name)
{
this.Name = Name;
Updated = false;
}
public bool Updated {get; private set;}
private string _Name = null;
public string Name
{
get { return _Name; }
set {
if (!_Name.Equals( value ))
{
_Name = value;
Updated = true
}
}
}
}

Resources