KentZhou
KentZhou

Reputation: 25573

How to get DataContext for UIElement?

As UIElement has no property DataContext, how can I get the DataContext for UIElement?

Upvotes: 2

Views: 2817

Answers (2)

Emond
Emond

Reputation: 50682

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

Upvotes: 10

Bill Reiss
Bill Reiss

Reputation: 3460

You should be able to cast the UIElement to a FrameworkElement and then access the DataContext property.

Upvotes: 0

Related Questions