I have created a custom control which inherits from DataGrid and adds a header property in the same way that HeaderedContentControl has a header.
[Bindable(true)]
public Object Header
{
get { return (Object)GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
}
// Using a DependencyProperty as the backing store for Header. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register("Header", typeof(Object), typeof(ExtendedDataGrid), new PropertyMetadata(null, HeaderProperty_Changed));
private static void HeaderProperty_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ExtendedDataGrid ctrl = (ExtendedDataGrid)d;
ctrl.OnHeaderChanged(e.OldValue, e.NewValue);
}
protected virtual void OnHeaderChanged(object oldValue, object newValue)
{
RemoveLogicalChild(oldValue);
AddLogicalChild(newValue);
}
The control template binds a ContentPresenter content to the HeaderProperty. (This is inside the Scrollviewer ControlTemplate inside the DataGrid ControlTemplate so I can't use ContentSource)
<ContentPresenter Grid.Row="0" Grid.ColumnSpan="99"
Margin="0"
Content="{Binding Header, RelativeSource={RelativeSource AncestorType{x:Type extended:ExtendedDataGrid}}}"/>
The content is set correctly to the header property.
I have found that the content presenter does not inherit the DataGrid DataContext so I have to set the DataContext separately. This means that any bindings inside the header will not bind as expected, because the DataContext for all Elements in the header is null. I can see from the ContentPresenter implementation that it specifically sets the DataContext to null on Initialise so I understand why this is happening.
Question
However the part I do not understand and I am interested to know is how the ContentPresenter elements in many other controls correctly inherit the DataContext without (from what I can see) any different code/xaml? For example the Button ContentPresenter or the HeaderContentControl ContentPresenters.
TemplateBinding
. – SinatrButton
sContentPresenter
is usingTemplateBinding
(100% sure). I am trying to understand what you are possible asking (if it's not a binding problem) and just can't understand ;)DataContext
? It can be set yes, it's inherited byButton
, but it's not used inButton
control template. So once again, what is your question? – Sinatr