WPF UserControl - SelectedItem of a Usercontrol DataGrid to bind to a ItemSource to DataGrid outside the UserControl

前端 未结 1 1249
南旧
南旧 2021-01-06 16:38

Hi, My WPF UserControl knowledge is like an hour old. So please forgive me if there are plenty of tutorials or/and answers on SO regarding this question (To be honest I

相关标签:
1条回答
  • 2021-01-06 17:08

    You can add a new dependency property to your custom usercontrol and bind your datagrid items source to that property. Make sure to handle selection changed event on your user control's data grid and set the dependency property to the selected item.

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

    handle the selection changed event

       public YourUserControl()
            {
                InitializeComponent();
                dgv.SelectionChanged += dgv_SelectionChanged; 
    
            }
    
        void dgv_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                MySelectedItem = dgv.SelectedItem;
            }
    

    and then bind to

    ItemsSource="{Binding ElementName=myUserControl, Path=MySelectedItem.CustomerOrders}"
    
    0 讨论(0)
提交回复
热议问题