I tried this:
Binding binding = new Binding("Content.DataContext");
BindingOperations.SetBinding(tab, DataContextProperty, binding);
It isn't working. I don't know why.
I tried this:
Binding binding = new Binding("Content.DataContext");
BindingOperations.SetBinding(tab, DataContextProperty, binding);
It isn't working. I don't know why.
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.
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.