CheckBox ListView control selection - wpf

I'm following MVVM pattern. I have a listview control which has multiple checkboxes.
my viewmodel has collection of Student which is bounded to listview control.
public ObservableCollection<Student> students{ get; private set; }
private ObservableCollection<Student> _displays { get; set; }
viewmodel doesn't know anything about the view so it doesn't access to the listview control
I tried by defining the Student class by below
public class Student: INotifyPropertyChanged
{
public string Name{ get; set; }
public string class { get; set; }
//Provide change-notification for IsSelected
private bool _fIsSelected = false;
public bool IsSelected
{
get { return _fIsSelected; }
set
{
_fIsSelected = value;
this.OnPropertyChanged("IsSelected");
}
}
}
now i want to perform some action in viewmodel when user select/deselect the checkbox.
how can achieve this? is it correct way to define above class?

Your Student class knows when its values change, so you just need to add a PropertyChanged handler to your collection of Student objects in the view model. In this way, your view model can get notified when the values of the Student classes change. Try something like this:
foreach (Student student in students)
{
student.PropertyChanged += Item_PropertyChanged;
}
...
private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsSelected")
{
// The IsSelected property was changed
}
}
Note that you will have to add a handler to every item in the collection. You could do that in a loop, as shown above, or by extending the ObservableCollection<T> class and overriding the Add, Insert andRemove methods and the constructors.
UPDATE >>>
Expanding on my final paragraph from above, you can extend the ObservableCollection<T> class and override the Add and Remove methods and the constructors... at its most basic, you could do something like this:
public class Students : ObservableCollection<Student>
{
public Students(IEnumerable<Student> students)
{
foreach (Student student in students) Add(student);
}
public new void Add(T item)
{
item.PropertyChanged += Item_PropertyChanged;
base.Add(item);
}
public new bool Remove(T item)
{
item.PropertyChanged -= Item_PropertyChanged;
return base.Remove(item);
}
private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
// Notify of all item property changes
NotifyPropertyChanged(e.PropertyName);
}
// Implement the INotifyPropertyChanged interface properly here
}
The benefit of this method is that you can then just attach one handler to the collection, rather than having to manually attach them to each item:
Students.PropertyChanged += Item_PropertyChanged;

Related

MVVM & business logic Layer

I have a problem with MVVM pattern and binding collection. My ViewModel provides a collection to the View but to get this collection I use this:
public BindingList<Car> BindingListCars { get; set; }
public CarsVm()
{
BindingListVoiture = carServices.ListCars;
}
When I bind my View on this List it's as if I bind directly my View on the Model because they use the same reference. So when I edit one property of a Car, the model is directly edited without using carServices validation method.
What is the best solution to correct this problem ?
Do I have to expose a copy of my Model to my View to not edit directly my Model from the View?
Do I have to use BindingList in my Model and subsribe to ListChanged in my carServices to validate each change?
You should either perform the validation directly in the Car class itself or expose wrapper objects instead of exposing the "real" Car objects to the view.
The following sample code should give you the idea about what I mean:
//the "pure" model class:
public class Car
{
public string Model { get; set; }
}
public class CarService
{
public List<CarWrapper> ListCar()
{
List<Car> cars = new List<Car>(); //get your Car objects...
return cars.Select(c => new CarWrapper(c, this)).ToList();
}
public bool Validate()
{
//
return true;
}
}
public class CarWrapper
{
private readonly Car _model;
CarService _service;
public CarWrapper(Car model, CarService service)
{
_model = model;
_service = service;
}
//create a wrapper property for each property of the Car model:
public string Model
{
get { return _model.Model; }
set
{
if(_service.Validate())
_model.Model = value;
}
}
}
Obviously if you expose an IEnumerable<Car> from your view model for the view to bind, you are effectively bypassing any validation that is dedined outside of the Car class if the view is able to set any properties of the Car class.
Thanks for your answer mm8,
With this solution I have to create one wrapper per class which need outside validation. It add work and during refactoring we have to edit the class and the Wrapper.
What do you think about this solution :
I put my list of vehicle in a binding list
My service subscribe to ListChanged event of this list
My service implement INotifyDataErrorInfo
For each modification in this list validation is executed
If there is an error ErrorsChanged event is raised
The view model subsribe to this event and retrieve error Data.
The view model subsribe to this event and retrieve error Data.
For example :
My services implementation :
public class VehicleServices : INotifyDataErrorInfo
{
private BindingList<Vehicle> _bindingListCar
public BindingList<Vehicle> BindingListCar
{
get return _bindingListCar;
}
private readonly Dictionary<string, ICollection<string>>
_validationErrors = new Dictionary<string, ICollection<string>>();
//INotifyDataErrorInfo implementation
public IEnumerable GetErrors(string propertyName)
public bool HasErrors
private void RaiseErrorsChanged(string propertyName)
public VehicleServices()
{
_bindingListCar = GetVehicles();
_bindingListCar.ListChanged += BindingListVehicleChanged;
}
private void BindingListVehicleChanged(object sender, ListChangedEventArgs e)
{
//Only modification is managed
if (e.ListChangedType != ListChangedType.ItemChanged) return;
switch(e.PropertyDescriptor.Name)
//Validate each property
//if there is ErrorsChanged is raised
}
}
And my ViewModel
public class CarVm : BindableBase
{
private ICollection<string> _errors;
public ICollection<string> Error
{
get
{
return _errors;
}
set
{
SetProperty(ref _errors, value);
}
}
private VehicleServices _carServices;
public BindingList<Vehicle> BindingListCar { get; set; }
public CarVm(VehicleServices carServices)
{
_carServices = carServices;
BindingListCar = new BindingList<Vehicle>(_carServices.BindingListCar);
_carServices.ErrorsChanged += _carServices_ErrorsChanged;
}
private void _carServices_ErrorsChanged(object sender, DataErrorsChangedEventArgs e)
{
Error = _carServices.ValidationErrors[e.PropertyName];
}
}
Do you think this is a good practice ?

Raising OnPropertyChanged in the setter of each property vs Instance of Object

Information for the question:
I am trying to understand how to properly implement INotifyPropertyChanged on objects and collections.
First, here is my ViewModelBase class:
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertychanged([CallerMemberName] string propertyName = "")
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Consider that I have a class called Person:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
}
To use INotifyPropertyChanged, most examples that I have seen change the Person class to something like this:
public class Person
{
public int Id { get; set; }
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertychanged();
}
}
private string _age;
public string Age
{
get { return _age; }
set
{
_age = value;
OnPropertychanged();
}
}
}
It seems to work exactly the same when used a single time on an instance of the object (This might be useful if there are a lot of properties):
private Person _person;
public Person MyPerson
{
get { return _person; }
set
{
_person = value;
OnPropertychanged();
}
}
Actual question:
1 - Does it make a difference (aside from amounts of code) whether you call OnPropertychanged() on each individual property verses on an instance of an object? (Are both considered good practice?)
2 - If setting OnPropertychanged() on the object instance is good practice, am I correct to create an ObservableCollection like this?:
var PersonCollection = new ObservableCollection<MyPerson>();
1) Well, if you want to call it on object instance, then you need to do it every time you use your class like this in binding. When you implement OnNotifyPropertyChanged directly inside your class, you don't need to care about it later on...
2) Classes with INotifyPropertyChanged do not require Observable collections. This is however must when you are binding colection do some UI control (ListBox, ListView) and want to add/remove its elements. Observable collection will then make sure the UI gets updated.
The ObservableCollections object... When adding and removing from this collection the UI will be notified of the changes (Top Level). If you have an "ObservableCollection of Person" and you change a property on the one of the objects(Person) in the list the UI will not update unless your "Person" class implements the INotifyPropertyChanged interface, which can be put into a base class that all classes can inherit from like your example. I hope this helps a little.

How to capture a property changed even of one view model in another view model

i have view model class A and it has the property "a".
and i have class called B , and it ha sproperty "b" where i store list of all A[] as list.
if any change in the property a , i would like to change the property in the parent class A.
that is
class B
{
property b1;
List A[]
}
Class A
{
property a1;
}
I am using MVVM and notify property chnaged event is there in both the places. what i dont know how to wire up both .
In my BaseCollection class which extends ObservableCollection<T>, I have a created a CollectionItemPropertyChanged delegate that I can attach a handler to, so I can be notified when property values have changed in any item in the collection:
public delegate void ItemPropertyChanged(T item, string propertyName);
Then I add a getter and setter of the type of the delegate:
public virtual ItemPropertyChanged CurrentItemPropertyChanged { get; set; }
To achieve this, I have to attach a handler to each item's PropertyChanged event:
public BaseCollection(IEnumerable<T> collection)
{
foreach (T item in collection) Add(item);
}
public new void Add(T item)
{
item.PropertyChanged += Item_PropertyChanged;
base.Add(item);
}
I also need to remove the handlers when objects are removed:
public new bool Remove(T item)
{
if (item == null) return false;
item.PropertyChanged -= Item_PropertyChanged;
return base.Remove(item);
}
Then there is the Item_PropertyChanged handler:
private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (CollectionItemPropertyChanged != null) CollectionItemPropertyChanged(
currentItem, e.PropertyName);
}
This can then be used in your class B like so:
public List<A> Items
{
get { return items; }
set
{
items = value;
items.CollectionItemPropertyChanged += YourHandler;
NotifyPropertyChanged(Items);
}
}
Then your handler:
private void YourHandler(A item, string propertyName)
{
// propertyName is the name of the changed property from the A object named item
}
To answer your question more directly, you can attach a handler from one view model to this delegate in another... for example:
Items.CollectionItemPropertyChanged += ViewModel2.YourHandler;
Or from the other view model:
ViewModel1.Items.CollectionItemPropertyChanged += YourHandler;
Create View Model A as Singleton and update the a property using that instance.

Implementing INotifyCollectionChanged interface

I need to implement a collection with special capabilities. In addition, I want to bind this collection to a ListView, Therefore I ended up with the next code (I omitted some methods to make it shorter here in the forum):
public class myCollection<T> : INotifyCollectionChanged
{
private Collection<T> collection = new Collection<T>();
public event NotifyCollectionChangedEventHandler CollectionChanged;
public void Add(T item)
{
collection.Insert(collection.Count, item);
OnCollectionChange(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
}
protected virtual void OnCollectionChange(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
CollectionChanged(this, e);
}
}
I wanted to test it with a simple data class:
public class Person
{
public string GivenName { get; set; }
public string SurName { get; set; }
}
So I created an instance of myCollection class as follows:
myCollection<Person> _PersonCollection = new myCollection<Person>();
public myCollection<Person> PersonCollection
{ get { return _PersonCollection; } }
The problem is that the ListView does not update when the collection updates although I implemented the INotifyCollectionChanged interface.
I know that my binding is fine (in XAML) because when I use the ObservableCollecion class instead of myCollecion class like this:
ObservableCollection<Person> _PersonCollection = new ObservableCollection<Person>();
public ObservableCollection<Person> PersonCollection
{ get { return _PersonCollection; } }
the ListView updates
What is the problem?
In order for your collection to be consumed, you should implement IEnumerable and IEnumerator too. Although, you're probably better off subclassing ObservableCollection<T>

DataGridViewColumn.DataPropertyName Property

I have a DataGridView control and I want to populate it with data.
I use DataSource property
// dgvDealAsset is DataGridView
private void DealAssetListControl_Load(object sender, EventArgs e)
{
dgvDealAssets.AutoGenerateColumns = false;
dgvDealAssets.DataSource = DealAssetList.Instance.Values.ToList();
}
Now problem number one. The class of my collection does not contain only simple types that I can map to columns using DataPropertyName. This is the class that is contained in collection.
class MyClass
{
public String Name;
MyOtherClass otherclass;
}
class MyOtherClass
{
public String Name;
}
Now I am binding properties of MyClass to columns
col1.DataPropertyName = "Name" // Ok
col2.DataPropertyName = "otherclass" // Not OK - I will have empty cell
The problem is that I want to display otherclass.Name field. But if I try to write
col2.DataPropertyName = "otherclass.Name"
I get empty cell.
I tried to manually set the column
private void DealAssetListControl_Load(object sender, EventArgs e)
{
dgvDealAssets.AutoGenerateColumns = false;
dgvDealAssets.DataSource = DealAssetList.Instance.Values.ToList();
// iterate through rows and set the column manually
foreach (DataGridViewRow row in dgvDealAssets.Rows)
{
row.Cells["Column2"].Value = ((DealAsset)row.DataBoundItem).otherclass.Name;
}
But this foreach cycle takes about minute to complete (2k elements). How to solve this problem?
DataGridView doesn't support databinding to child properties. For more info, check this post
I like the solution that uses the CellFormatting event.
Problem nr.1:
Try to do the following:
extend MyOtherClass from Object (this step might not be needed)
and override, or create, method ToString().
That should do it.
In case you want to use many child elements like this:
class MyClass
{
public int Id;
public MyOtherClass OtherClass;
}
class MyOtherClass
{
public string Name;
public int Number;
}
How about
1st solution
Set value for each cell in some event (mabye other one is better), manually, after setting datasource, for example:
private void dgv_CellFormatting( object sender, DataGridViewCellFormattingEventArgs e )
{
MyClass data = dgv.Rows[ e.RowIndex ].DataBoundItem as MyClass;
dgv.Rows[ e.RowIndex ].Cells[ "colName" ].Value = data.OtherClass.Name;
dgv.Rows[ e.RowIndex ].Cells[ "colNumber" ].Value = data.OtherClass.Number;
}
2nd solution
What about creating a DataTable from the data and then bind it?
I'd be thankful for any opinion ;-)
It sounds like the DataGridView's virtual mode would solve your problem. In virtual mode, the DataGridView will fire an event whenever it needs to display a cell. The event lets you populate the cell however you please. The advantage of virtual mode is the system only needs to pull the data that's actually being displayed, so there's no slow start-up time while you load everything.
private void my_init_function() {
datagridview.VirtualMode = true;
datagridview.CellValueNeeded += new System.Windows.Forms.DataGridViewCellValueEventHandler(datagridview_CellValueNeeded);
}
private void datagridview_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
e.Value = get_my_data(e.RowIndex, e.ColumnIndex);
}
The way of databinding a specific column of a datagrid to a child property of the datagrid's datasource is using the DataGridView.Column.Tag property, along with the ToString() override method inside the child object. It goes as follows:
public class Car
{
public int Id { get; set; }
public int Name { get; set; }
public string Colour { get; set; }
public Wheel Wheel { get; set; }
}
public class Wheel
{
public string WheelName { get; set; }
public override string ToString()
{
return WheelName;
}
}
public class Main
{
private void LoadGrid(List<Car> data)
{
this.dataGridView.Columns["Wheel"].Tag = "WheelName";
}
}

Resources