WPF UserControl - UserControl DataGrid的SelectedItem,用于将ItemSsource绑定到UserControl外部的DataGrid

时间:2014-04-30 06:55:46

标签: c# wpf xaml datagrid user-controls

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

因此,在创建UserControl之前,我有一个数据网格,可以根据用户在文本框中输入的文本来筛选客户。找到后,该过滤器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。 (如上所述)

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

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

好一点啰嗦但我希望你能理解这个问题,而且我已经掌握了足够的知识。如果我做错了,请告诉我,然后向下投票。

干杯

1 个答案:

答案 0 :(得分:3)

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

   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}"