.Net WPF DataGrid - change foreground color programatically

Daruk

Honorary Master
Joined
Jul 18, 2008
Messages
35,837
#1
I'm not a full time coder as this will show and haven't done a lot with WPF. I have a DataGrid called dataGrid and I want the colour of a row to be changed when the user double clicks it. So far I have this but i'm missing the piece about updating the foreground colour for the row clicked:

xaml:
Code:
        <DataGrid x:Name="dataGrid">
            <DataGrid.Columns>
                <DataGridTextColumn Header="User name" Binding="{Binding Username}" Width="130"></DataGridTextColumn>
                <DataGridTextColumn Header="Full name" Binding="{Binding Fullname}" Width="243"></DataGridTextColumn>
                <DataGridCheckBoxColumn Header="Enabled" Binding="{Binding Enabled}" Width="57"></DataGridCheckBoxColumn>
            </DataGrid.Columns>
            <DataGrid.Resources>
                <Style TargetType="DataGridRow">
                    <EventSetter Event="MouseDoubleClick" Handler="Row_DoubleClick"/>
                </Style>
            </DataGrid.Resources>
        </DataGrid>
c#:
Code:
        private void Row_DoubleClick(object sender, RoutedEventArgs e)
        {
        //update the row foreground colour to Brushes.Blue***
        }
Seems it should be easy but I'm really struggling with this one. What am I missing? I've tried countless stackoverflow suggestions but nothing is working just yet. Any help is appreciated!
 

Hamster

Resident Rodent
Joined
Aug 22, 2006
Messages
30,146
#2
Sho....this brings back memories. I'm completely out of touch with C# and WPF these days but from what you've posted I would inspect the sender object in the event. It's most like a reference to the row that was clicked or the datagrid (in which case the event arg may hold data like the row number).
 

Kosmik

Honorary Master
Joined
Sep 21, 2007
Messages
18,471
#3
Not a wpf person myself, do you not maybe need to do a rebind or refresh of the control after setting the color?
 

Hamster

Resident Rodent
Joined
Aug 22, 2006
Messages
30,146
#4
I was curious so I googled it for you. As suspected, you can use the sender object:
https://stackoverflow.com/questions/22790181/wpf-datagrid-row-double-click-event-programmatically

Code:
private void Row_DoubleClick(object sender, MouseButtonEventArgs e)
  {
     DataGridRow row = sender as DataGridRow;
     // Some operations with this row
  }
WPF is driven by databindings. I didn't read all of it but the correct way to do this is probably define a style for a specific row state and then alter the state on the click event.

ie. "selected" is "red" so when I double click a row all the other rows are not selected and this one is.
 
Top