WPF 通过 DataGrid 选择的行作为命令参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16563661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:48:04  来源:igfitidea点击:

WPF pass DataGrid selected row as command parameter

wpfbinding

提问by John Smith

  1. MainWindowViewModelhas a ViewCustomerCommand(string id)command that shows a customer by id
  2. MainWindow.xamlcontaining TabControl
  3. TabControl has a UserControl that contains DataGrid that is bind to Customers collection
    | id | customer |
  1. MainWindowViewModel有一个ViewCustomerCommand(string id)命令,它按 id 显示客户
  2. 包含 TabControl 的MainWindow.xaml
  3. TabControl 有一个包含绑定到客户集合的 DataGrid 的 UserControl
    | 身 | 客户 |

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

如何将 DataGrid 选定行中的“id”列作为MainWindow.xaml 中的命令参数传递

MainWindow.xaml
    <Button Command="{Binding ViewCustomerCommand}" CommandParameter="??? how to pass id of selected customer ???" />

回答by DHN

Well if you really need to expose the SelectedItemfrom within a UserControlwhy don't you extend it with such a property?

好吧,如果您真的需要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); }
    }
}

So now you can bind the SelectedItemof the DataGridin the UserControlto its SelectedItemproperty.

所以现在你可以绑定SelectedItemDataGridUserControl它的SelectedItem属性。

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

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

现在,你只需要找到一种方法来访问SelectedItem的性能TabItem。但我要把那部分留给你。

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

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