As UIElement
has no property DataContext
, how can I get the DataContext
for UIElement
?
Asked
Active
Viewed 2,615 times
2

Dave Clemmer
- 3,741
- 12
- 49
- 72

KentZhou
- 24,805
- 41
- 134
- 200
2 Answers
10
The DataContext
property is introduced to the inheritance hierarchy in the FrameworkElement
.
Because FrameworkElement
inherits from UIElement
you have to make sure the UIElement
actually is a FrameworkElement
:
if(uiElement is FrameworkElement frameworkElement)
{
var dc = frameworkElement.DataContext;
}

Emond
- 50,210
- 11
- 84
- 115
0
You should be able to cast the UIElement
to a FrameworkElement
and then access the DataContext
property.

Dave Clemmer
- 3,741
- 12
- 49
- 72

Bill Reiss
- 3,460
- 1
- 19
- 20
-
With all due respect, this is not good advice. It is perfectly legal to create custom UI elements by deriving directly from `UIElement`, and this is perhaps even preferred if you want a lighter-duty control and/or don't need or want the additional layout and data-handling capabilities of `FrameworkElement`. Since the existence of non-FE controls can't be ruled out, "casting the `UIElement` to `FrameworkElement`" seems like shaky advice considering how little information was given by the OP. – Glenn Slayden Jun 29 '18 at 23:46