Mion Sion 241reputation points
good evening everyone
I've been trying to get this to work for almost a week but for the life of me I can't get it to work the way I want it to
What I want to do is that when a filter is applied, it also applies an orange color to the applied column button.
As you can see in the picture here I somehow got it to work,
so let the color appear on the column and button you want on the button only
This filter is associated with the site name so I just want the button color to be orange for this button and if the filter is removed I want it to go back to transapant,
Below is mine
main view model
public MainViewModel() { ColumnFilters = new dictionary(); elfenload = new LoadDatabases(); FilterCommand = new RelayCommand(filter); ApplyFilterCommand = new RelayCommand(Apply Filter); CurrentFilters = new ObservableCollection(); elfentafel = new Dictionary>(); _databases = new ObservableCollection() Filtered databases = νέα ObservableCollection() //Pumps = new ObservableCollection(); FilterTextChangedCommand = new RelayCommand(obj => FilterTextChanged(obj as string)); elfenload.InitialzePumps(); foreach(var item in elfenload.Pumps) { FilteredDatabases.Add(item); _databases.Add(item); foreach (var item in elfenload.Pumps) { foreach (var prop in typeof(LoadDatabases).GetProperties()) { var columnName = prop.Name; var columnValue = prop.GetValue(item)?.ToString(); if (!string.IsNullOrEmpty(columnValue)) { if (!elfentable.ContainsKey(columnName)) { // If the column name is not in the dictionary, add it to the new collection elfentable[columnName] = new ObservableCollection(); } var filters = elementable[column name]; if (!filters.Any(f => f.Title == columnValue)) { // If the filter is not in the collection, add the filters. Add(new filter { Title = columnValue, IsChecked = true, FilterColor = false } ); } } } elfenviewsource = new CollectionViewSource(); elfenviewsource.Source = elfenload.Pumps; //filter database(); // elfendatagrid.ItemsSource = elfenviewsource.View; / elfenviewsource.Filter += elfenviewsource_Filter; } public void FilterTextChanged(string filterText) { var searchQuery = filterText; FilterView.Filter = item => { var filter = item as filter; if (filter == null) return false; return filter .Title .IndexOf(searchQuery, StringComparison.OrdinalIgnoreCase) >= 0; }; } public void Search(object parameter) { var searchQuery = parameter as String; FilterView.Filter = item => { var filter = item as filter; if (filter = = null) return false; return filter.Title.Contains(searchQuery); }; } public dictionaryIsFilterApplied { get { dictionaryresults = new Dictionaryforeach(var key in ColumnFilters.Keys) { result[key] = IsFilterAppliedToColumn(key); } return result? } } private ICommand _isFilterAppliedCommand; public ICommand IsFilterAppliedCommand { get { if (_isFilterAppliedAppliedApplied) mand( param => this.IsFilterAppliedToColumn(param as string), param => param is string); } return _isFilterAppliedCommand; } } public bool IsFilterAppliedToColumn(string columnName) { return ColumnFilters.ContainsKey(columnFilters.ContainsKey(columnFilters.ContainsKey(columnFilters)&nlumncolumn } public void ApplyFilter(object obj) { FilterDatabases(); // Update ColumnFilters after filtering the database / // Check that CurrentFilteredColumn is not empty or an empty string } // You can use CurrentFilteredColumn anywhere you need a column name // in Update column filters after filtering ; if (ColumnFilters[key]) { // If a filter on the column has been applied, change FilterColor to true foreach(var filter in elfentable[key]) { filter.FilterColor = true; } } // Check if the filter is applied to the current column } else { FilteredColumnName = null; // If the filter has been removed , set it to null } //CurrentFilteredColumn = obj.ToString(); OnPropertyChanged(nameof(ColumnFilters)); OnPropertyChanged(nameof (CurrentFilteredColumn)); } public void FilterDatabases() { FilteredDatabases.Clear(); foreach (var db in _databases) { if (ShouldAccept(db)) { FilteredDatabases.Add(db); } } //foreach(elfentable.Keys var key in ) / /{ // ColumnFilters[key] = elfentable[key]. Any(filter => filter.IsChecked); //} OnPropertyChanged("FiltersApplied"); OnPropertyChanged(nameof(filtereddatabases)); } private bool ShouldAccept(Load)Bases { string ColName = ""; round number; try { foreach (var item in ld.GetType().GetProperties()) { ColName = item.Name; var propertyValue = ld.GetType(). GetProperty(ColName).GetValue(ld, null); continue if (propertyValue == null); // go to next iteration if value is null string value = propertyValue.ToString(); if (elfentable.ContainsKey(ColName)) { ObservableCollectionelfstream; elfentable.TryGetValue(ColName, from elfencurrent); count = 0; if(elvencurrent!= null) { count = elfencurrent.Where(w => w.IsChecked).Count(w => w.Title == value) ; if (count == 0) { return false; } } } } } catch { return true; } return true; } public void Filter (object parameter) { IsPopupOpen = true; string colName = parameter as string; CurrentFilteredColumn = colName; if (elfentable.ContainsKey(colName)) { elfentable.TryGetValue(colName, out var elfencurrent); CurrentFilters.Clear(); foreach (var item in elfencurrent) { CurrentFilters.Add(item); } } // remove filter Reset the FilterColor of all filters to false foreach (var filter in CurrentFilters) { filter.FilterColor = false; } FilterView = CollectionViewSource.GetDefaultView(CurrentFilters); OnPropertyChanged(nameof(FilterView)); OnPropertyChanged(name-filtered));
filter class,
ιδιωτικό boolean _IsChecked; δημόσιο boolean IsChecked { get { return _Ischecked; } set { _Ischecked = value; OnPropertyChanged(nameof(IsChecked)); }} private string _Title; public string Title { get { return _Title; value;OnPropertyofTang ));}} ιδιωτικό bool _FilterColor = false; δημόσιο bool FilterColor { get { return _FilterColor; } set { _FilterColor = value; OnPropertyChanged(nameof(FilterColor)); } }
And finally the xaml code,
< /DataTemplate> < RowDefinition Height="Auto" />
converter
ColumnFilterToBrushConverter: IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo Culture) { if (values.Length!= 2) return Brushes.Transparent; var columnName = values[0] as String; var columnFilters = values[1] as Dictionary;if (Kolomnaam == null || columnFilters == null) return Brushes.Transparent; if (columnFilters.ContainsKey(columnName) && columnFilters[columnName]) return Brushes.Orange; return par Brushes.Tran } public object[] ConvertBack(object value, Type[] targetTypes, parameter objectcultuur, CultureInfo) {gooi nieuwe NotImplementedException(); } }
Honestly any help would be greatly appreciated
I've been trying to get it to work for a week but I can't get it to work with columns and buttons,
regards,
elfenliedtopfan5
Windows Demo Foundation
Windows Demo Foundation
Part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,357 questions
Log in to follow
0{tel} lift
Hui Liu-MSFT 17,221 peoplereputation points •Microsoft supplier
2023-05-22T02:56:57.6633333+00:00 Hello @mionshion. Welcome to Microsoft Q&A. I cannot reproduce your problem. I would like to confirm the following details with you.
what is your full password
database laden
class? and what is its definitionelfenviewbron
,filter view
,current filter column
,filter column name
InIsPopupOpen
in your password? Does the definition I added to the code below match yours?This filter is associated with the site name so I just want the button color to be orange for this button and if the filter is removed I want it to go back to transapant,
Want to change the color of the circled button?
Mion Sion 241reputation points
(Video) WPF Controls | 24 -RadioButton | HD | RadioButton in WPF2023-05-22T22:34:08.2533333+00:00 @Hui Liu - MSFTThe full code for loaddata is
public class LoadDatabases: ViewModelBase { public static SQLiteConnection connectionstring = new SQLiteConnection($"Data Source=C:\\Users\\elfenliedtopfan5\\Downloads\\ConfigListing.sqlite;foreign keys=true?"); #region loadpumpdata public IEnumerable
GetPumpData() { if (!File.Exists("C:\\Users\\elfenliedtopfan5\\Downloads\\ConfigListing.sqlite")) { Console.WriteLine("Geen databasebestand gevonden!"); Return Enumerable.Empty () } List resultList = new list (); try { //string getdb = "select * from HydraPOS"; //SQLiteCommand elfeninfo = new SQLiteCommand(getdb, connectionstring); // open connection(); openconnection(); // attach database String attachDb = " DATABASE LOCATION 'C:\\Users\\elfenliedtopfan5\\Downloads\\ConfigListing.sqlite' AS AttachedDb?"; SQLiteCommand attachCommand = new SQLiteCommand(attachDb, connection string); "attachedCommand.Execdery (startQuery) = "Attached. .HydraPOS"; // Note the table name change SQLiteCommand elfeninfo = new SQLiteCommand(getdb, connectionstring); SQLiteDataReader result = elfeninfo.ExecuteReader(); if (result.HasRows) { while (result.Read()) { / / Get fields here string _SiteName = result["Site"].ToString(); String_Version = result["Version"].ToString(); String_Bunkering = result["Bunkering"].ToString() ;String _PumplinkHostAddress = Result[" PumplinkHost" " "].ToString(); SiteName = _SiteName; Version = _Version; Bulk = _Bunkering; PumplinkHost = _PumplinkHostAddress; _PumplinkHostAddress)); } } else { Console.WriteLine("The HydraPOS table has no rows!"); } close band(); } catch (Exception ex) { Console.WriteLine("Error retrieving data from HydraPOS table: " + ex.Message); } return list result; } #endregion public LoadDatabases(String SiteName, String Version, String Bunkering, String PumplinkHostAddress) { this.SiteName = SiteName;this.Version = Version;this.Bunkering = Bunkering; this.PumplinkHost = PumplinkHostAddress; } public LoadDatabases() { } public void InitialPs({Pumple) (); Pump.Clear(); // Never update, always delete, otherwise the data connection will be broken for each (var pumpData in GetPumpData()) { Pumps.Add(pumpData); } } private ObservableCollection _Pumps; public ObservableCollection Pumps { get { return _Pumps; } set { _Pumps = value; OnPropertyChanged(nameof(Pumps)); } } #region check connection public void OpenConnection() { if (connectionstring.State != System.Data.ConnectionState.Open) { connectionstring.Open(); } } public void CloseConnection() { if (connectionstring.State != System.Data.ConnectionState.Closed) { connectionstring.Close(); } } #endregion ιδιωτική συμβολοσειρά _SiteName; δημόσια συμβολοσειρά SiteName { get { return _SiteName; } set { _SiteName = value; OnPropertyChanged(name(SiteName)); } } private string _Version; public string Έκδοση { get { return _Version; } set { _Version = value; OnPropertyChanged(name(version)); } } private string _Bunkering; δημόσια συμβολοσειρά Bunkering { get { return _Bunkering; } set { _Bunkering = value; OnPropertyChanged(nameof(Bunker)); } } private string _PumplinkHost; public string PumplinkHost { get { return _PumplinkHost; }set { Return _PumplinkHost; OnPropertyChanged(nameof(PumplinkHost)); } } } The current filter column is used to determine whether a filter is applied or not. I have tried many different things to make it work. Most of what's here is the code I added to try and fix why it changes all the filter columns and sorry for checking the popup
So each column shows all the items in each column
What I want to do is, when I apply a filter, say site name,
So here for example garage lock is selected say deselect all and press apply filter. I want the background of the [X] button to change to orange and only in this columnI want it to turn gray when the filter is removed, but I can't
I would have a button to compare to all other columns if that makes sense
All the other things you see there, if you look in, they will point to itapply_filter(method)
and filter(method)Here I am trying to change the colors or determine if they should change color because the apply filter method is executed when the apply filter button is pressed
The popup usually comes from bindings and xaml
Thank you very much for your comment.
Hui Liu-MSFT 17,221 peoplereputation points •Microsoft supplier
2023-05-23T06:28:48.9833333+00:00 Hallo,@Mion Sion.I tried to complete the code and hit [×] but it didn't reproduce your environment and results. Is the problem not reproducible because of my RelayCommand code?
Is it possible to provide the full code that reproduces the problem? Or you can look at my code below and show me the code and steps that can reproduce the problem to reproduce the problem and analyze the problem. Please show me other code, including style code, that reproduces the problem.
xaml:
< DataGridTextColumn Header="version" Binding="{binding version}"/> code return:
public class MainViewModel: INotifyPropertyChanged {public Dictionary
ColumnFilters { get; private LoadDatabases elfenload; public RelayCommand FilterCommand { get; } public RelayCommand ApplyFilterCommand { get; } public ObservableCollection CurrentFilters { get; } public CollectionViewSource elfenviewsource { get;private collection; } private dictionary > elfentafel; private ObservableCollection _databases; openbare ObservableCollection Filtered databases { get; } public string CurrentFilteredColumn { get; private set? } public string FilteredColumnName { get; private set? } public bool IsPopupOpen { get; put down? } public RelayCommand FilterTextChangedCommand { get; private ICollectionView publicView; send back icv? } set { icv = value; OnPropertyChanged("Display filter"); } } public MainViewModel() { LoadDatabases.LoadData(); ColumnFilters = new dictionary (); elfenload = new LoadDatabases(); FilterCommand = new RelayCommand(filter); ApplyFilterCommand = new RelayCommand(Apply Filter); CurrentFilters = new ObservableCollection (); elfentafel = new Dictionary >(); _databases = new ObservableCollection () Filtered databases = νέα ObservableCollection () //Pumps = new ObservableCollection (); FilterTextChangedCommand = new RelayCommand(obj => FilterTextChanged(obj as string)); elfenload.InitialzePumps(); foreach(var item in elfenload.Pumps) { FilteredDatabases.Add(item); _databases.Add(item); foreach (var item in elfenload.Pumps) { foreach (var prop in typeof(LoadDatabases).GetProperties()) { var columnName = prop.Name; var columnValue = prop.GetValue(item)?.ToString(); if (!string.IsNullOrEmpty(columnValue)) { if (!elfentable.ContainsKey(columnName)) { // If the column name is not in the dictionary, add it to the new collection elfentable[columnName] = new ObservableCollection (); } var filters = elementable[column name]; if (!filters.Any(f => f.Title == columnValue)) { // If the filter is not in the collection, add the filters. Add(new filter { Title = columnValue, IsChecked = true, FilterColor = false } ); } } } elfenviewsource = new CollectionViewSource(); elfenviewsource.Source = elfenload.Pumps; //filter database(); // elfendatagrid.ItemsSource = elfenviewsource.View; / elfenviewsource.Filter += elfenviewsource_Filter; } public void FilterTextChanged(string filterText) { var searchQuery = filterText; FilterView.Filter = item => { var filter = item as filter; if (filter == null) return false; return filter .Title .IndexOf(searchQuery, StringComparison.OrdinalIgnoreCase) >= 0; }; } public void Search(object parameter) { var searchQuery = parameter as String; FilterView.Filter = item => { var filter = item as filter; if (filter = = null) return false; return filter.Title.Contains(searchQuery); }; } public dictionary IsFilterApplied { get { dictionary results = new Dictionary foreach(var key in ColumnFilters.Keys) { result[key] = IsFilterAppliedToColumn(key); } return result? } } private ICommand _isFilterAppliedCommand; public ICommand IsFilterAppliedCommand { get { if (_isFilterAppliedAppliedApplied) mand( param => this.IsFilterAppliedToColumn(param as string), param => param is string); } return _isFilterAppliedCommand; } } public bool IsFilterAppliedToColumn(string columnName) { return ColumnFilters.ContainsKey(columnFilters.ContainsKey(columnFilters.ContainsKey(columnFilters)&nlumncolumn } public void ApplyFilter(object obj) { FilterDatabases(); // Update ColumnFilters after filtering the database / // Check that CurrentFilteredColumn is not empty or an empty string } // You can use CurrentFilteredColumn anywhere you need a column name // in Update column filters after filtering ; if (ColumnFilters[key]) { // If a filter on the column has been applied, change FilterColor to true foreach(var filter in elfentable[key]) { filter.FilterColor = true; } } // Check if the filter is applied to the current column } else { FilteredColumnName = null; // If the filter has been removed , set it to null } //CurrentFilteredColumn = obj.ToString(); OnPropertyChanged(nameof(ColumnFilters)); OnPropertyChanged(nameof (CurrentFilteredColumn)); } public void FilterDatabases() { FilteredDatabases.Clear(); foreach (var db in _databases) { if (ShouldAccept(db)) { FilteredDatabases.Add(db); } } //foreach(elfentable.Keys var key in ) / /{ // ColumnFilters[key] = elfentable[key]. Any(filter => filter.IsChecked); //} OnPropertyChanged("FiltersApplied"); OnPropertyChanged(nameof(filtereddatabases)); } private bool ShouldAccept(Load)Bases { string ColName = ""; round number; try { foreach (var item in ld.GetType().GetProperties()) { ColName = item.Name; var propertyValue = ld.GetType(). GetProperty(ColName).GetValue(ld, null); continue if (propertyValue == null); // go to next iteration if value is null string value = propertyValue.ToString(); if (elfentable.ContainsKey(ColName)) { ObservableCollection elfstream; elfentable.TryGetValue(ColName, from elfencurrent); count = 0; if(elvencurrent!= null) { count = elfencurrent.Where(w => w.IsChecked).Count(w => w.Title == value) ; if (count == 0) { return false; } } } } } catch { return true; } return true; } public void Filter (object parameter) { IsPopupOpen = true; string colName = parameter as string; CurrentFilteredColumn = colName; if (elfentable.ContainsKey(colName)) { elfentable.TryGetValue(colName, out var elfencurrent); CurrentFilters.Clear(); foreach (var item in elfencurrent) { CurrentFilters.Add(item); } } // remove filter Reset the filter color of all filters to false foreach (var filter in CurrentFilters) { filter.FilterColor = false; } FilterView = CollectionViewSource.GetDefaultView(CurrentFilters); OnPropertyChanged(nameof(FilterView)); OnPropertyChanged(nameoffilterranged}); andler PropertyModified; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class LoadDatabases: ViewModelBase { public static void LoadDatate()BQ" { S. ; SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=testDB.db"); m_dbConnection.Open(); string sql = "create tabular data ( AUTOINCREMENT PRIMARY KEY INTEGER ID, Pumps Si varchar(20), Version (20), varchar(20), Bunkering varchar(20) ,PumplinkHost varchar(20) )"; SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection); command. ExecuteNonQuery();sql = "INSERT INTO data(Pumpsion,Punker,Bun, ,PumplinkHost) VALUES('pump1', 'POS00801 Mellors Garage-HPOS1','4.7.40.2',','127.0.0.1')"; command = new SQLiteCommand(sql, m_dbConnection); cuteNond;sql = "INSERT INTO data(Pumps, Site, Version, Bunkering, PumplinkHost) VALUES('pump2', 'Pos00754 LLANBEDR AIRFIELD-HYDRA1','4.7.40.2',' ','192.165'; command 0." new SQLiteCommand(sql, m_dbConnection);command.ExecuteNonQuery(); sql = "INSERT INTO data(Pumps,Site, Version,Bunkering,PumplinkHost) VALUES('pump3', 'Pos00752 LLANHBEDR '.200752 LLANHBEDR ,' ','192.168.0.251')"; command = new SQLiteCommand(sql, m_dbConnection); command.ExecuteNonQuery(); m_dbConnection.Close(); } public static SQLiteConnection connection string SQLiteConnection =New SQLiteConnection=ConnectionSQLite \\Users\\elfenliedtopfan5\\Downloads\\ConfigListing.sqlite;foreign keys=true?"); public IEnumerable GetPumpData() { List resultList = new list (); try { SQLiteConnection m_dbConnection = new SQLiteConnection("Datasource=testDB.db"); m_dbConnection.Open(); SQLiteCommand sqlCom = new SQLiteCommand("Select * from data", m_dbQLiteConnection.Recute. ); if (result.HasRows) { while (result.Read()) { string _SiteName = result["Site"].ToString(); string _Version = result["Version"].ToString(); string _Bunkering = Result["Bunkering"].ToString(); String _PumplinkHostAddress = Result["PumplinkHost"].ToString(); Site Name = _Site Name; Version = _Version; Fuel = _Bunkering; PumplinkHost = _PumplinkHostAddress; , _Bunkering, _PumplinkHostAddress)); } } else { Console.WriteLine("HydraPOS table has no rows!"); } close bond(); } catch (Exception ex) { Console.WriteLine("Error retrieving data from HydraPOS table: " + ex.Message); } return list result; } public LoadDatabases(String SiteName, String Version, String Bunkering, String PumplinkHostAddress) { this.SiteName = SiteName; this.Version = Version; dit.Bunker = Bunker; this.p PumplinkHostAddress; } public LoadDatabases() { } public void InitialzePumps() { Pumps = new ObservableCollection (); Pump.Clear(); // Never update, always delete, otherwise the data connection will be broken for each (var pumpData in GetPumpData()) { Pumps.Add(pumpData); } } private ObservableCollection _Pumps; public ObservableCollection Pumps { get { return _Pumps; } set { _Pumps = value; OnPropertyChanged(nameof(Pumps)); } } #region check connection public void OpenConnection() { if (connectionstring.State != System.Data.ConnectionState.Open) { connectionstring.Open(); } } public void CloseConnection() { if (connectionstring.State != System.Data.ConnectionState.Closed) { connectionstring.Close(); } } #endregion ιδιωτική συμβολοσειρά _SiteName; δημόσια συμβολοσειρά SiteName { get { return _SiteName; } set { _SiteName = value; OnPropertyChanged(name(SiteName)); } } private string _Version; public string Έκδοση { get { return _Version; } set { _Version = value; OnPropertyChanged(name(version)); } } private string _Bunkering; δημόσια συμβολοσειρά Bunkering { get { return _Bunkering; } set { _Bunkering = value; OnPropertyChanged(nameof(Bunker)); } } private string _PumplinkHost; _PumplinkHost; } settings { _PumplinkHost = value; OnPropertyChanged(nameof(Bunker)); ; } } } public class RelayCommand: ICommand { private read-only action result:
Log in to comment
2 answers
Order by:more helpful
more helpful Topical senior
Mion Sion 241reputation points
2023-05-23T20:50:56.3133333+00:00 I've compressed the project file for viewing, the only thing I can't include is the database itself as actual data, but the project code is here,
https://www.mediafire.com/file/fmx84oixiqlx7iw/DatabaseFiltering.zip/file
Here's the full project.
Mion Sion 241reputation points
2023-05-23T20:52:42.8033333+00:00 @Hui Liu - MSFT
Log in to comment
Hui Liu-MSFT 17,221 peoplereputation points •Microsoft supplier
(Video) C# - WPF Desktop App - Edit Employees (DataGrid & Row Double Click Event)2023-05-24T03:11:54.67+00:00 Hello @mionshion. The button activation background problem in DataGridColumnHeader, you can use the following code.
result:
If the answer is helpful to you, click "accept the answer"and I like.
notes:Follow our stepsdocumentEnable email notifications if you want to receive email notifications on this topic.
Mion Sion 241reputation points
2023-05-24T20:20:20.31+00:00 Yes it looks great - when you first apply it if you uncheck it or do something with the filter on the column it basically highlights all the buttons I want
So by default they are all checked and no filter is applied so if you uncheck any of them the website name will be highlighted in orange and if you check all again the filter will be removed
vise fresh with all the others, if you uncheck anything in the version it will be highlighted orange until the filter is applied, and if you recheck all values and no filter is applied it will go back to transparent and remove the orange background
Also sorry for the late reply if I explain well, I work 12 hour shifts but I hope I understand, sorry for the unclear explanation,
regards,
Minor
Log in to comment
Log in to reply
Activity
Log in to track issues and users