Abdulsattar Mohammed
Abdulsattar Mohammed

Reputation: 10712

How do you bind the DataContext of a Control to the DataContext of its Content in WPF?

I tried this:

Binding binding = new Binding("Content.DataContext");
BindingOperations.SetBinding(tab, DataContextProperty, binding);

It isn't working. I don't know why.

Upvotes: 0

Views: 594

Answers (2)

Aviad P.
Aviad P.

Reputation: 32629

There is probably a better way to achieve what you're trying to do with bindings in XAML, but if you're using code behind anyway, you might try the following instead:

FrameworkElement fe = tab.Content as FrameworkElement
if (fe != null)
    tab.DataContext = fe.DataContext;

Without any binding.

Upvotes: 0

itowlson
itowlson

Reputation: 74802

You haven't specified a source for the binding. It is therefore using the local DataContext of the tab element. Since the tab element doesn't yet have a DataContext (it's what you're trying to set), let alone one for which the path Content.DataContext is meaningful, this isn't going to work.

Instead use something like:

Binding binding = new Binding("Content.DataContext")
{
  RelativeSource = RelativeSource.Self
};
BindingOperations.SetBinding(tab, DataContextProperty, binding);

(Depending on your exact requirement you might also want to investigate using Binding.Source instead of Binding.RelativeSource.)

The RelativeSource setting specifies that the binding is to the same element as the binding target rather than to the local DataContext -- thus, the DataContext of the control is now bound to the DataContext of the Content of that same control, as required.

Upvotes: 2

Related Questions