COMBOBOX filtering in WPF with MVVM - wpf

I am developing an application using WPF mvvm approach.
I have a requirement where I have to show a list of items in a combo box for selection.
Based on some flag I need to filter out few items from the combo box for selection.
I tried to use two different items sources one with full list and another with filtered list and based on the flag I wanted to change the items source.
This does not seem to be working well. Is there any easy way to apply filters on the existing list based on some flag ?

There are lots of different ways to do this but my personal preference is to use a ListCollectionView as the ItemsSource of the control displaying the filtered list, to set a filter predicate on ListCollectionView.Filter and to call ListCollectionView.Refresh when the filter parameters change.
The example below will filter a list of countries based on their continent.
Code
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
public class FilteringViewModel : INotifyPropertyChanged
{
private ObservableCollection<Country> _countries;
private ContinentViewModel _selectedContinent;
public ListCollectionView CountryView { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<ContinentViewModel> Continents { get; set; }
public FilteringViewModel()
{
_countries =
new ObservableCollection<Country>(
new[]
{
new Country() { Continent = Continent.Africa, DisplayName = "Zimbabwe" },
new Country() { Continent = Continent.Africa, DisplayName = "Egypt" },
new Country() { Continent = Continent.Europe, DisplayName = "United Kingdom" }
});
CountryView = new ListCollectionView(_countries);
CountryView.Filter = o => _selectedContinent == null || ((Country)o).Continent == _selectedContinent.Model;
Continents = new ObservableCollection<ContinentViewModel>(Enum.GetValues(typeof(Continent)).Cast<Continent>().Select(c => new ContinentViewModel { Model = c}));
}
public ContinentViewModel SelectedContinent
{
get
{
return _selectedContinent;
}
set
{
_selectedContinent = value;
OnContinentChanged();
this.OnPropertyChanged("SelectedContinent");
}
}
private void OnContinentChanged()
{
CountryView.Refresh();
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class Country
{
public string DisplayName { get; set; }
public Continent Continent { get; set; }
}
public enum Continent
{
[Description("Africa")]
Africa,
Asia,
Europe,
America
}
public class ContinentViewModel
{
public Continent Model { get; set; }
public string DisplayName
{
get
{
return Enum.GetName(typeof(Continent), Model);
}
}
}
XAML
<StackPanel Orientation="Vertical">
<ComboBox ItemsSource="{Binding Continents}" SelectedItem="{Binding SelectedContinent}" DisplayMemberPath="DisplayName" />
<ListBox ItemsSource="{Binding CountryView}" DisplayMemberPath="DisplayName" />
</StackPanel>

Is there any easy way to apply filters on the existing list based on
some flag ?
Although your question is not clear, but I think you don't need to maintain two list just to get the filter data. You can use simple LINQ to do the filtering. Suppose if you have a ViewModel Property like
public IEnumerable<ComboBoxItem> Data
{
get ;
set ;
}
And you want to filter that based on some bool values then you can write something like
ViewModel.Data.ToList().Where(item => item.Status).ToList()
Status can be the bool based on that you want to filter your data and you can add this bool inside your ComboBoxItem class.

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. !!!

Tick the checkbox column in WPF datagrid through code

I have an ObservableCollection of items in which one of the property is bool.
When i set the itemsSource of the datagrid as the ObservableCollection, it auto-generates the column with checkbox column for the bool property.
I would like to know how we can tick the checkbox in code, lets say if we have the mark all option?
I tried updating the ObservableCollection records property value with true, but it doesnt help updating the UI.
Please help.
[EDIT: Below code works as suggested in the answer]
My Class is as follows
public class InvoiceDoc : INotifyPropertyChanged
{
private bool _Selected;
[DisplayName("Selected")]
public bool Selected
{
get { return _Selected; }
set { _Selected = value; this.OnPropertyChanged(); }
}
[DisplayName("Date")]
public DateTime DocDate { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged !=null)
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
The datagrid is as follows
<DataGrid x:Name="dgInvoices" Margin="32,110,32,59" AutoGeneratingColumn="dgInvoices_AutoGeneratingColumn"/>
setting the ItemsSource is as follows
docs = new ObservableCollection<InvoiceDoc>(); ;
dgInvoices.ItemsSource = docs;
I am expecting the grid to auto check the check box once is set the value in the collection.
Binding to an ObservableCollection is only reactive if an Item is added or removed.
Your elements inside your Collection have to implement INotifyPropertyChanged so the UI recognises the changes
EDIT:
Lets say you have the following objects in your Collection:
public class MyClass {
public string Name { get; set; }
public bool IsActive { get; set; }
}
This class has now to be modified to the following:
public class MyClass : INotifyPropertyChanged{
private string _name;
private bool _isActive;
public string Name
{
get { return this._name; }
set { this._name = value; this.OnPropertyChanged();}
}
public bool IsActive
{
get { return this._isActive; }
set { this._isActive = value;
this.OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null) {
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
If there are any Errors, remove the CallerMemberNameAttribute and invoke the this.OnPropertyChanged(); with the Propertyname.

WPF Databound object changed in code not reflected in UI

WPF-MVVM beginner here.
My problem: in a WPF-MVVM UI I am editing an entity. Some properties when changed, require automatic updates on other properties. These are done in Entity class, set methods, but not reflected in my View
More details:
1) I have the Model (a simple class with properties) in a separate assembly (not WPF related since is the general business model). Note that "SomeOption" when set to false, requires some other options to automatically be changed.
Example:
public class Employee : BaseEntity
{
public string EmployeeNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
....
private bool someOption
public bool SomeOption {
get
{ return someOption}
set {
someOption= value;
if (!value)
{
OtherOption = false;
OtherProperty= "";
AndAnotherOption= false;
}
}
}
}
2) The WPF UI has a base ViewModel implementing INotifyPropertyChanged. The current edited record (Employee) is a public property of the ViewModel:
public Employee SelectedEmployee
{
get { return _selectedEmployee; }
set
{
if (_selectedEmployee != value)
{
_selectedEmployee = value;
OnPropertyChanged(nameof(SelectedEmployee));
}
}
}
3) When un-checking the checkbox bound to "SomeOption", the other properties which are changed in entity code, are not reflected on the View, and stay on the screen as edited by user.
Please let me know what I am missing. Thanks!
You should implement INotifyPropertyChanged in your model to update entities at your UI. For example:
public class Employee : BaseEntity, INotifyPropertyChanged
{
private string employeeNumber;
public string EmployeeNumber {
get{return employeeNumber};
set
{
employeeNumber=value;
OnPropertyChanged("EmployeeNumber");
}
//...Other properties...
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChangedEvent(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Employee needs to implement INotifyPropertyChanged just as your viewmodel does, and fire PropertyChanged on changes to its own properties (the ones you're calling OtherOption, OtherProperty, etc.)
What you've got now will update the UI when the view model selects a different Employee, but subsequent changes to that Employee don't send any notifications.

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.

MVVM pattern filter listview and update on new item

I've been struggling with this problem for a couple of days, but somewhere I obviously on a wrong track. Situation is as follows: I have a window with 3 buttons (Add New Task, Show Inbox, Show Today) and a Listview. My TaskViewModel class is has a ObservableCollection of TaskModel, with pretty simple Filter functionality. My class looks as follows:
public class TaskViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public ObservableCollection<TaskModel> TaskCollection { get; private set; }
public TaskViewModel()
{
TaskDataAccess ac = new TaskDataAccess();
this.TaskCollection = ac.GetAllTasks();
}
public ICommand AddTaskCommand
{
get { return new DelegateCommand(this.AddTask); }
}
public ICommand FilterInboxCommand
{
get { return new DelegateCommand(this.FilterInbox); }
}
public void AddTask()
{
this.TaskCollection.Add(new TaskModel(9, "I", "New Item for testing"));
this.GetListCollectionView().Filter = this.IsInbox; ;
}
private void FilterInbox()
{
this.GetListCollectionView().Filter = this.IsInbox;
}
....
}
The filter functionality works fine, but when I call the new window "Add new task" it does not update the listview (here: this.TaskCollection.Add(new TaskModel(9, "I", "New Item for testing"));
I'd appreciate if someone could give me a hint...
Try to do this...
create a private field (say _taskCollection) to backup your property TaskCollection.
private readonly ObservableCollection<TaskModel> _taskCollection;
Then remove the private setter from TaskCollection property. Also remove the constructor code that loads the collection.
Instead write your getter this way...
public ObservableCollection<TaskModel> TaskCollection {
get {
if (this._taskCollection == null)
{
TaskDataAccess ac = new TaskDataAccess();
this._taskCollection = ac.GetAllTasks();
}
return this._taskCollection;
}
}
Let me know if this way works ....

Resources