.NET Framework Developer Center >
.NET Development Forums
>
Windows Presentation Foundation (WPF)
>
Get object from DataContext
Get object from DataContext
- I have a user control that I created which is a Navigation Bar used with Collections.
When I place the UserControl on a WPF form I connect its DataContext directly to a business object that is based on a Collection(of T). From here I get the CollectionView and can use MoveCurrentToFirst, MoveCurrentToLast, etc.
If I instead set the DataContext to a binding object whose path is the same Collection(of T), then I cannot cast the UserControl.DataContext into a Collection(of T) and therefore have no access to MoveCurrentTo....
My question is: How can I get the object from the DataContext?
UserControl.DataContext.GetType.Name = Binding
TryCast(UserControl.DataContext, Collection(of Object)) = nothing
I don't know what else to try?
Rick
Answers
- Hi Rick,
Could you tell me how you bind the DataContext property of the UserControl?
Suppose the business object is as follows:
Collection(of YourType) datasource = new Collection(of YourType);
You can bind the DataContent of the UserControl as follows:
Binding b = new Binding();
b.Source = datasource;
userControl1.SetBinding(UserControl1.DataContextProperty, b);
The value of the UserControl is of type Collection(of YourType), so you can cast it to the type of Collection(of YourType) as follows:
Collection(of YourType) ds = userControl1.DataContext as Collection(of YourType);
Sincerely,
Linda Liu
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.- Marked As Answer byLinda LiuMSFT, ModeratorWednesday, November 18, 2009 8:55 AM
All Replies
- Hi Rick,
Could you tell me how you bind the DataContext property of the UserControl?
Suppose the business object is as follows:
Collection(of YourType) datasource = new Collection(of YourType);
You can bind the DataContent of the UserControl as follows:
Binding b = new Binding();
b.Source = datasource;
userControl1.SetBinding(UserControl1.DataContextProperty, b);
The value of the UserControl is of type Collection(of YourType), so you can cast it to the type of Collection(of YourType) as follows:
Collection(of YourType) ds = userControl1.DataContext as Collection(of YourType);
Sincerely,
Linda Liu
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.- Marked As Answer byLinda LiuMSFT, ModeratorWednesday, November 18, 2009 8:55 AM
- Thank you for the response Linda,
I just had a hard drive crash in my development laptop an need to recover.
I'll come back in a day or two to this thread.
Rick


