C
C#15mo ago
mblla

❔ Illuminate buttons pressing a row of a DataGrid

Hello! I have a bigger project but to resolve a question I made another one, as an example to show the behavior I want my application to have, continue as follows. I have a People model with basic properties (name, age, and a random boolean) As I am using the MVVM design pattern I am passing a list of People, "previously created in the ViewModel", to a DataGrid that has 2 columns Name and age, and below some buttons, "The behavior I want it to have is that, while I select a row of the datagrid, the buttons change color depending on the boolean of my object passed by list" (Be careful, the behavior does not make much sense, but I would like to do this for another personal project) I have searched for Chat Gpt, and it has given me a solution with triggers, but it has not worked for me. If anyone could help me, I'd be grateful.
15 Replies
Kippachu
Kippachu15mo ago
When you select a row, does all buttons have to change color, or only the one with the same name on it ?
mblla
mblla15mo ago
Change only those that have true in their IsOk property Sorry for my english, I'm translating it The DataGrid receives a list of the People object that has several properties and the IsOk is one of them, it is a boolean, and it does not matter which row is selected, just by selecting a row, it performs the color change
Kippachu
Kippachu15mo ago
I found the solution 🙂
Kippachu
Kippachu15mo ago
This is my result when selecting John, when John isOk = true and Jav isOk = false
Kippachu
Kippachu15mo ago
You'll need to implement INotifyPropertyChanged inside People class then add :
private SolidColorBrush _buttonColor;
public SolidColorBrush ButtonColor
{
get => _buttonColor;
set
{
_buttonColor = value;
OnPropertyChanged(nameof(ButtonColor));
}
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private SolidColorBrush _buttonColor;
public SolidColorBrush ButtonColor
{
get => _buttonColor;
set
{
_buttonColor = value;
OnPropertyChanged(nameof(ButtonColor));
}
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
In MainWindow.xaml bind Button Background to ButtonColor property, also in DataGrid properties, add SelectedCellsChanged and create the method DataGrid_SelectedCellsChanged Like this : <DataGrid Margin="20,5,20,5" SelectedCellsChanged="DataGrid_SelectedCellsChanged" Height="200" Width="600" ItemsSource="{Binding MyListOfPeopleForBinding}" AutoGenerateColumns="False"> You have to create this method inside MainWindow.xaml.cs private void DataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e) { if (sender is not DataGrid dataGrid) return; var vm = DataContext as MainViewModel; var selectedPerson = dataGrid.SelectedItem as People; vm?.UpdateButtonColors(selectedPerson); } Add the method UpdateButtonColors(People selectedPerson) in your viewModel or it will not work : public void UpdateButtonColors(People selectedPeople) { foreach (var person in MyListOfPeople) { if (selectedPeople == null) { person.ButtonColor = Brushes.Gray; // Default color } else { person.ButtonColor = person.IsOk ? Brushes.Green : Brushes.Red; } } } I don't know if my solution is the best, maybe it's bad idk but it works, tell me if you succeeded Basically when you select a row then your variable "selectedPerson" in DataGrid_SelectedCellsChanged will not be null, so inside UpdateButtonColors the else case will be run, changing the color of every people in your MyPeopleList, and as you binded the buttons colors to your people color, it will also change, else if unselect the row the selectedPerson will be null and will set the buttons color back to grey
mblla
mblla15mo ago
Awesome! I'm gonna try do my self
Kippachu
Kippachu15mo ago
Maybe the triggers way was better and it does everything you need in two lines, but i don't know i did it like this I'm still learning also
mblla
mblla15mo ago
What I didn't know was how to pass the list that was sent by binding to the code behind my view to be able to operate, but I couldn't change colors either, I'll try to do it myself, Thank you very much for your time!!
Kippachu
Kippachu15mo ago
No problem, tell me if it worked, now i can go to eat ^^
mblla
mblla15mo ago
That's what it told me when I asked ChatGpt, but there were things that it didn't even allow to compile, and I couldn't find a solution. I found this discord by microsoftLearn, while reading documentation about triggers haha
mblla
mblla15mo ago
Works!
mblla
mblla15mo ago
Now I'm going to try to understand how it works haha, thanks!
Kippachu
Kippachu15mo ago
Hey I just came back, I'm glad to hear you made it If you don't understand something in the code you can ask me
mblla
mblla15mo ago
I found a way to do, only with trigers, but only works to change on all button, but, I'm trying to found how can do for one button unique This is de code in de View
<Window.Resources> <Style TargetType="{x:Type Button}"> <Setter Property="Background" Value="Gray"/> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=myDataGrid, Path=SelectedItem.IsOK}" Value="True" > <Setter Property="Background" Value="Green" /> </DataTrigger> <DataTrigger Binding="{Binding ElementName=myDataGrid, Path=SelectedItem.IsOK}" Value="False" > <Setter Property="Background" Value="Red" /> </DataTrigger> </Style.Triggers> </Style> </Window.Resources>
Accord
Accord15mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts
❔ WPF System.ObjectDisposedException: 'Cannot access a closed Stream.'I have a wpf application and when I navigate from Page A to page B then back to Page A, the xaml ini❔ Returns the left pointer, why?https://leetcode.com/problems/first-bad-version/solutions/3403742/binary-search-solution-for-c-compl❔ Error passing builder.Configuration as argument - .net 7As you can see I am passing the builder.Configuration as an argument to my ConfigureIdentityServices❔ Where to store the app service app settings variable so I can access them based on environmentIn azure app service, currently I'm maintaining the application setting variable. In the local how t❔ Error CS0017Im doing a graded assignment and im working on it myself; Im stuck at this one line that is telling GIT Question for companySorry if this is a really noob question, but I don't want to bother my manager and also I've never w✅ Debugging razor component page isn`t workingCould you please tell me why the debugger on the .razor page may not work? On the page to which visu❔ How to read configuration based on environmentI have a stored my connection string as configuration in web.config. Now I have stored the same conn❔ PlayStation 2 startup recreationWondering how I can recreate the iconic PS2 startup, and whag framework would fit this question❔ Send using http post with multiple parameters, to an endpoint defined in C# with minimal APIsI've got an endpoint like so: ```csharp app.MapPost("/endpoint1", async ValueTask<IResult?> (string