c# - WPF UserControl - Usercontrol DataGrid 的 SelectedItem 绑定(bind)到 UserControl 外的 DataGrid 的 ItemSource

标签 c# wpf xaml datagrid user-controls

您好,我的 WPF UserControl 知识只有一个小时了。因此,如果有很多关于这个问题的教程或/和答案,请原谅我(老实说,我认为这无法完成,需要重新编写代码……因此我想问的原因)

因此,在创建 UserControl 之前,我有一个数据网格,它根据用户在文本框中键入的文本筛选客户。一旦找到,该筛选器 DataGrid 的 SelectedItem 将用于绑定(bind)到包含新集合的新 DataGrid。

所以……

过滤数据网格 XAML

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

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

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

ItemsSource="{Binding SelectedCustomer.CustomerOrders}"

一切都很好,一切正常。

但是,我将在我的项目中大量使用此筛选客户结果功能,因此我创建了一个 UserControl,其中筛选器 DataGrid 正在运行。

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

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

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

好吧有点啰嗦,但我希望你能理解这个问题,而且我已经提供了足够的关于手头主题的知识。如果我做错了什么,请告诉我并否决这个问题。

干杯

最佳答案

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

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

然后绑定(bind)到

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

关于c# - WPF UserControl - Usercontrol DataGrid 的 SelectedItem 绑定(bind)到 UserControl 外的 DataGrid 的 ItemSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23381560/

相关文章:

wpf - 如何修复圆角按钮中边框和背景之间的空白区域?

visual-studio - 无法加载文件或程序集 Microsoft.Expression.Interactions 和 GalaSoft.MvvmLight.Extras.WPF4

c# - Azure函数应用程序-写入blob

c# - Elasticsearch NEST API-查询正确的索引

c# - 像 Linq to DataTable 中的运算符?

c# - 当另一个进程退出时在 C# 中引发事件

xaml - 自定义 XAML 微调器

c# - WPF饼图如何在切片之间添加空间?

wpf - 从 WPF 到 WinForms 的气泡鼠标事件

WPF WebBrowser 文档完成事件