I have an ObservableCollection
called States
in the States
Model I have id, name, code, country
I would like to keep this collection with all of them but I would like to make a new collection to filter only the country. Currently I have this working by using this:
ViewModel.cs
StateCollectionView = CollectionViewSource.GetDefaultView(States);
StateCollectionView.Filter += StatesFilter;
public static void GetStates()
{
States.Clear();
using var conn = new SqlConnection(Settings.Default.ConnectionString);
conn.Open();
string qry = "SELECT * FROM dbo.State";
var cmd = new SqlCommand(qry, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
States.Add(new States(reader));
}
conn.Close();
}
public static bool StatesFilter(object state)
{
bool result = true;
if (state is States states)
{
if (states.Country)
{
Debug.Print(states.Name);
return true;
}
else
{
return false;
}
}
return result;
}
This is working by filtering the ObservableCollection
of States
but I would not like to filter that collection but rather create a ICollectionViewSource
and use that in the binding in the view. As I need the States
ObservableCollection
to not be filtered to display correct data in other views.
I am trying to bind it to a ComboBox
on the country drop down I want it to only show counties and the states dropdown to only show states. They are set apart by a bool value in the database.
EDIT: Sample
StateCollectionView = CollectionViewSource.GetDefaultView(States);
CountryCollectionView = CollectionViewSource.GetDefaultView(States);
StateCollectionView.Filter += StatesFilter;
CountryCollectionView.Filter += CountryFilter;
public static void GetStates()
{
States.Clear();
using var conn = new SqlConnection(Settings.Default.ConnectionString);
conn.Open();
string qry = "SELECT * FROM dbo.State";
var cmd = new SqlCommand(qry, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
States.Add(new States(reader));
}
conn.Close();
}
private static bool StatesFilter(object state) => state is States states && !states.Country;
private static bool CountryFilter(object state) => state is States states && states.Country;
public static ObservableCollection<States> States { get; set; } = new ObservableCollection<States>();
public static ICollectionView StateCollectionView { get; set; }
public static ICollectionView CountryCollectionView { get; set; }