Button in a column, getting the row from which it came on the Click event handler

后端 未结 5 512
眼角桃花
眼角桃花 2020-11-29 17:52

I\'ve set the itemsource of my WPF Datagrid to a List of Objects returned from my DAL. I\'ve also added an extra column which contains a button, the xaml is below.



        
相关标签:
5条回答
  • 2020-11-29 18:17
    MyObject obj= (MyObject)((Button)e.Source).DataContext;
    
    0 讨论(0)
  • 2020-11-29 18:20

    Another way which binds to command parameter DataContext and respect MVVM like Jobi Joy says button inherits datacontext form row.

    Button in XAML

    <RadButton Content="..." Command="{Binding RowActionCommand}" 
                             CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=DataContext}"/>
    

    Command implementation

    public void Execute(object parameter)
        {
            if (parameter is MyObject)
            {
    
            }
        }
    
    0 讨论(0)
  • 2020-11-29 18:28

    Basically your button will inherit the datacontext of a row data object. I am calling it as MyObject and hope MyObject.ID is what you wanted.

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyObject obj = ((FrameworkElement)sender).DataContext as MyObject;
        //Do whatever you wanted to do with MyObject.ID
    }
    
    0 讨论(0)
  • 2020-11-29 18:34

    Another way I like to do this is to bind the ID to the CommandParameter property of the button:

    <Button Click="Button_Click" CommandParameter="{Binding Path=ID}">View Details</Button>
    

    Then you can access it like so in code:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        object ID = ((Button)sender).CommandParameter;
    }
    
    0 讨论(0)
  • 2020-11-29 18:40

    If your DataGrid's DataContext is a DataView object (the DefaultView property of a DataTable), then you can also do this:

    private void Button_Click(object sender, RoutedEventArgs e) {
       DataRowView row = (DataRowView)((Button)e.Source).DataContext;
    }
    
    0 讨论(0)
提交回复
热议问题