【问题标题】:WPF UserControl - SelectedItem of a Usercontrol DataGrid to bind to a ItemSource to DataGrid outside the UserControlWPF UserControl - 将用户控件 DataGrid 的 SelectedItem 绑定到 ItemSource 到 UserControl 之外的 DataGrid
【发布时间】:2025-12-14 03:50:02
【问题描述】:

嗨,我的 WPF UserControl 知识已经有一个小时了。所以,如果有很多关于这个问题的教程或/和答案,请原谅我(老实说,我不认为这是可以做到的,需要重新编写代码......因此我认为我要问) em>

所以在创建用户控件之前,我有一个数据网格,它根据用户在文本框中键入的文本过滤客户。找到后,该过滤器 DataGrid 的 SelectedItem 将用于绑定到包含新集合的新 DataGrid。

所以……

过滤 DataGrid XAML

SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"
ItemsSource="{Binding Source={StaticResource cvsCustomers}}"

一旦用户在该网格中选择了一个客户,

一个新的 DataGrid 将包含基于 SelectedCustomer 的属性行

ItemsSource="{Binding SelectedCustomer.CustomerOrders}"

一切都很好,而且效果很好。

但是,我将在我的项目中大量使用此过滤客户结果功能,因此我创建了一个 UserControl,过滤器 DataGrid 在其中工作。

我已将此 UserControl 放在视图中,所以问题是我需要将 Usercontrol 中的 selectedItem 绑定到视图中的 DataGrid。 (如上)

所以我在视图中的 DataGrid 中需要这样的东西。

ItemsSource="{Binding ElementName=myUserControl, Path=SelectedCustomer.CustomerOrders}"

好吧,有点啰嗦,但我希望你能理解这个问题,并且我已经就手头的主题提供了足够的知识。如果我做错了什么,请告诉我,然后对这个问题投反对票。

干杯

【问题讨论】:

标签: c# wpf xaml datagrid user-controls


【解决方案1】:

您可以将新的依赖属性添加到您的自定义用户控件,并将您的数据网格项目源绑定到该属性。确保在用户控件的数据网格上处理选择更改事件并将依赖属性设置为所选项目。

   public object MySelectedItem
        {
            get { return (object)GetValue(MySelectedItemProperty); }
            set { SetValue(MySelectedItemProperty, value); }
        }

    // Using a DependencyProperty as the backing store for MySelectedItem.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MySelectedItemProperty =
        DependencyProperty.Register("MySelectedItem", typeof(object), typeof(YOURUSERCONTROLTYPE), new UIPropertyMetadata(null));

处理选择更改事件

   public YourUserControl()
        {
            InitializeComponent();
            dgv.SelectionChanged += dgv_SelectionChanged; 

        }

    void dgv_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MySelectedItem = dgv.SelectedItem;
        }

然后绑定到

ItemsSource="{Binding ElementName=myUserControl, Path=MySelectedItem.CustomerOrders}"

【讨论】:

  • 嗨,Deva,看起来很明智。我现在正在做其他事情,但我会尽可能地测试并标记为正确,谢谢!
  • @Marko Devcic,它有效,但仅以一种方式。即,将值从DataGrid 传递到DependencyProperty。但是如果我想传回价值呢?从外部代码到DataGrid
最近更新 更多