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

标签 wpf binding

  1. MainWindowViewModel 有一个按 id 显示客户的 ViewCustomerCommand(string id) 命令
  2. MainWindow.xaml 包含 TabControl
  3. TabControl 有一个 UserControl,其中包含绑定(bind)到 Customers 集合的 DataGrid
    |编号 |客户|

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

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

最佳答案

那么,如果您真的需要从 UserControl 中公开 SelectedItem,为什么不使用这样的属性来扩展它呢?

例如

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

现在您可以将 UserControlDataGridSelectedItem 绑定(bind)到它的 SelectedItem 属性。

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

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

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

关于WPF 将 DataGrid 选定的行作为命令参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16563661/

相关文章:

wpf - 如何使用单选按钮 "IsChecked"属性控制文本框的可见性?

c# - varchar 列自行排序

wpf - .NET WPF图表/图形

c# - 启动期间在 Main-Method 中获取 WPF 应用程序中的键盘状态

wpf - 您如何避免不确定的进度条卡住?

用于自定义声波控制的 WPF Performance 渲染

wpf - 将 String[] 转换为 Expando 以在 WPF 中绑定(bind) DataGrid

C# WPF - TreeView 与字典绑定(bind)

binding - 协议(protocol)的 Monotouch 绑定(bind)语法

c++ - 将带有存储在 std::function 中的捕获子句的 lambda 转换为原始函数指针