Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF pass DataGrid selected row as command parameter

Tags:

binding

wpf

  1. MainWindowViewModel has a ViewCustomerCommand(string id) command that shows a customer by id
  2. MainWindow.xaml containing TabControl
  3. TabControl has a UserControl that contains DataGrid that is bind to Customers collection
    | id | customer |

How do I pass "id" column in DataGrid selected row as a command parameter in MainWindow.xaml

MainWindow.xaml
    <Button Command="{Binding ViewCustomerCommand}" CommandParameter="??? how to pass id of selected customer ???" />
like image 848
John Smith Avatar asked Oct 27 '25 22:10

John Smith


1 Answers

Well if you really need to expose the SelectedItem from within a UserControl why don't you extend it with such a property?

E.g.

public class MyUserControl : UserControl
{
    private static readonly SomeType SelectedItemProperty = 
        DependencyProperty.Register("SelectedItem", typeof(SomeType), typeof(MyUserControl));

    public SomeType SelectedItem
    {
        get { return (SomeType)GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }
}

So now you can bind the SelectedItem of the DataGrid in the UserControl to its SelectedItem property.

<MyUserControl>
    <DataGrid SelectedItem="{Binding SelectedItem, 
              RelativeSource={RelativeSource FindAncestor, 
              AncestorType={x:Type MyUserControl}}" />
</MyUserControl>

Now you only have to find a way to access the SelectedItem property in the TabItem. But I'm leaving that part to you.

Please note, that this is only an illustration of my idea and it may contain some small errors.

like image 103
DHN Avatar answered Oct 29 '25 19:10

DHN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!