简体   繁体   中英

Getting the row on the button_click event inside a DataGrid column in WPF

I want to recover this thread . I have the same situation, but any of the solutions is working for me. I have the following xml, as you can se similar to the one ask:

  <DataGrid Grid.Column="1" Name="Info_DG" FontSize="18" CellEditEnding="Info_DG_CellEditEnding" >
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding BM}"/>
                <DataGridTextColumn Binding="{Binding BC}"/>
                <DataGridTemplateColumn>                        
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Click="Button_Click"></Button>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>

My objective is the same as the thread : to get the row number of the pressed button, but any of the listed solutions works for me.

Both of the following solutions are not working, both DataContext and ID are null in my case:

MyObject obj = ((FrameworkElement)sender).DataContext as MyObject;


object ID = ((Button)sender).CommandParameter;

The other answers are also base in DataContext, thus is not working as it is null. Is there anything wrong in my code as it gives me a null datacontext?

I think you are missing the ItemSource?

<DataGrid ItemSource="{Binding YourItemSource}" Grid.Column="1" Name="Info_DG" FontSize="18" CellEditEnding="Info_DG_CellEditEnding" >
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding BM}"/>
            <DataGridTextColumn Binding="{Binding BC}"/>
            <DataGridTemplateColumn>                        
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Click="Button_Click"></Button>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

With your Data Context issue, it is better to understand what is Data Context first, please read the below link. The below post explains in the easiest way of how to assign your Data Context which is step 1. However, you should always link your Data Context to a View Model (which is step 2).

https://www.wpf-tutorial.com/data-binding/using-the-datacontext/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM