WPF将DataGrid选中的行作为命令参数传递

时间:2013-05-15 11:19:01

标签: wpf binding

  1. MainWindowViewModel 有一个 ViewCustomerCommand(字符串ID)命令,按ID显示客户
  2. MainWindow.xaml 包含TabControl
  3. TabControl有一个UserControl,其中包含绑定到Customers集合的DataGrid
    | id |客户|
  4. 如何将DataGrid选定行中的“id”列作为 MainWindow.xaml

    中的命令参数传递
    MainWindow.xaml
        <Button Command="{Binding ViewCustomerCommand}" CommandParameter="??? how to pass id of selected customer ???" />
    

1 个答案:

答案 0 :(得分:4)

好吧,如果你真的需要在SelectedItem中公开UserControl,为什么不用这样的属性扩展它呢?

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); }
    }
}

现在,您可以将SelectedItemDataGrid的{​​{1}}绑定到其UserControl属性。

SelectedItem

现在,您只需要找到一种方法来访问<MyUserControl> <DataGrid SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MyUserControl}}" /> </MyUserControl> 中的SelectedItem属性。但是我要把那部分留给你了。

请注意,这只是我的想法的一个例证,它可能包含一些小错误。

相关问题