WPF用户控件 - 将UserControl DataGrid的SelectedItem绑定到UserControl外部DataGrid的ItemSource

3

你好,我关于WPF用户控件的知识只有一个小时。如果这个问题有很多教程或者在SO上有很多答案,请原谅我(老实说我不认为这是可以完成的,需要重新编写代码……因此我想问一下)。

在创建一个用户控件之前,我有一个数据网格,根据用户在文本框中输入的文本过滤客户信息。找到后,该过滤数据网格的SelectedItem被用于绑定到一个包含新集合的新数据网格。

所以……

过滤数据网格XAML

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

一旦用户在网格中选择了客户,一个新的数据网格将包含基于选定客户的属性行。
ItemsSource="{Binding SelectedCustomer.CustomerOrders}"

一切都很好,它可以工作。

然而,在我的项目中,我将经常使用这个“过滤客户结果”功能,因此我创建了一个UserControl,其中过滤DataGrid正常工作。

我将这个UserControl放在一个视图中,所以问题是我需要将Usercontrol中的selectedItem绑定到视图中的DataGrid。(就像上面那样)

因此,我需要在视图中的DataGrid中添加类似以下的内容。

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

好的,有点冗长,但我希望你能理解问题,并且我已经提供了足够的相关知识。如果我做错了什么,请告诉我并且只需对这个问题进行反对。

谢谢


请查看以下答案:https://dev59.com/dYHba4cB1Zd3GeqPNSWF#28224531 - bugged87
1个回答

5

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

   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,看起来很合理。我现在正在处理其他事情,但是我会在有时间的时候测试并标记为正确,谢谢! - user3428422
1
@Marko Devcic,它可以工作,但只能单向传值。也就是说,从DataGrid传递值到DependencyProperty。但是如果我想要反向传值呢?从外部代码传递值到DataGrid - monstr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接