Search code examples
c#wpfdatagrid

Get the value of the current cell and the next cell on SelectedCellsChanged event


I am having a WPF datagrid using MVVM pattern. I need to get the value of current cell and the adjacent cell when the focus is changed from the current cell. This is my XAML

<DataGrid x:Name="dgOptions" Grid.Row="1" SelectedCellsChanged="dgOptions_SelectedCellsChanged">
       <materialDesign:DataGridTemplateColumn x:Name="optValueColumn" Width="1*" CellTemplateSelector="{StaticResource TemplateSelector}">
            <materialDesign:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <Grid materialDesign:FocusManager.FocusedElement="{Binding ElementName=optValueColumn}"/>
                </DataTemplate>
            </materialDesign:DataGridTemplateColumn.CellEditingTemplate>
            <materialDesign:DataGridTemplateColumn.Header>
                <TextBlock Text="Value" TextWrapping="Wrap" TextAlignment="Center"/>
            </materialDesign:DataGridTemplateColumn.Header>
        </materialDesign:DataGridTemplateColumn>

        <materialDesign:DataGridTemplateColumn x:Name="optDefaultValueColumn" Visibility="Hidden" CellTemplateSelector="{StaticResource TemplateSelector}"/> 
</DataGrid> 

I have a SelectedCellsChanged event already that does some focus stuff. I need to get the value of optValueColumn and optDefaultValueColumn in this event. Since this has nothing to do with the business logic, I have decided to do it in code behind itself.

How do I get the values?

Or Is there any better way to get the same in other events?


Solution

  • Try this in the SelectedCellsChanged:

    var cellContent = optValueColumn.GetCellContent(e.AddedCells.First().Item);
    if(cellContent is ContentPresenter presenter)
    {
        var content = presenter.Content;
    }
    

    Since I dont know your CellTemplate, your cellContent may be a different type than ContentPresenter