问题描述
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 dont think this can be done and will need to re-do code... hence why I thought I ask)
So before creating a UserControl, I had a datagrid that fliters customers based on what text the user typed in a Textbox. Once found, the SelectedItem of that filter DataGrid is then used to bind to a new DataGrid containing a new collection.
So....
Filter DataGrid XAML
SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"
ItemsSource="{Binding Source={StaticResource cvsCustomers}}"
Once the User selects a Customer in that grid,
a new DataGrid would contain rows of properties based on the SelectedCustomer
ItemsSource="{Binding SelectedCustomer.CustomerOrders}"
All well and good and it works.
However, I am going to use this Filter Customer results functionality a lot in my project, so I have created a UserControl in which the filter DataGrid is working.
I have put this UserControl in a view, so the problem is I need whatever the selectedItem is in the Usercontrol to be bounded to a DataGrid in the view. (Like above)
So I need something like this in the DataGrid in the View.
ItemsSource="{Binding ElementName=myUserControl, Path=SelectedCustomer.CustomerOrders}"
Ok a bit long winded but I hope you understand the problem, and I have given enough knowledge on the subject at hand. If I done something wrong, please tell me and just down vote the question.
Cheers
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}"
这篇关于WPF UserControl - 将用户控件 DataGrid 的 SelectedItem 绑定到 ItemSource 到 UserControl 之外的 DataGrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!