4
  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 ???" />

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, @DHN. Your answer helped so much with a solution I did as you told and created a SelectedCustomer property and bind it to DataGrid <UserControl> <DataGrid SelectedItem="{Binding SelectedCustomer}" /> </UserControl> And command parameter passed like following MainWindow.xaml <Button Command="{Binding ViewCustomerCommand}" CommandParameter="{Binding Path=Tabs[0].SelectedCustomer.Id}" />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.