2014-11-14 34 views
0

我已經創建了一個自定義控件,該控件從DataGrid繼承,並以HeaderedContentControl具有標頭的相同方式添加標題屬性。ContentPresenter繼承DataContext

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

控件模板將ContentPresenter內容綁定到HeaderProperty。 (這是內部的ScrollViewer的ControlTemplate數據網格的ControlTemplate內,所以我不能使用ContentSource)

<ContentPresenter Grid.Row="0" Grid.ColumnSpan="99" 
        Margin="0" 
        Content="{Binding Header, RelativeSource={RelativeSource AncestorType{x:Type extended:ExtendedDataGrid}}}"/> 

的內容被正確地設置到頭部屬性。

我發現內容展示器不會繼承DataGrid DataContext,所以我必須單獨設置DataContext。這意味着頭中的任何綁定都不會按預期進行綁定,因爲頭中所有元素的DataContext都爲null。我可以從ContentPresenter實現中看到它在Initialise上專門將DataContext設置爲null,所以我明白爲什麼會發生這種情況。

問題

但是部分我不明白,我想知道的是如何在衆多其他控件ContentPresenter元素都能正常繼承,而不在DataContext(從我所看到的)任何不同的代碼/ XAML ?例如Button ContentPresenter或HeaderContentControl ContentPresenter。

+0

在控制模板中,您必須使用'TemplateBinding'。 – Sinatr 2014-11-14 14:14:06

+0

請解釋這將如何幫助我。正如我所說的ContentPresenter是在ScrollViewer ControlTemplate中,所以TemplateBinding會給我不正確的結果。 – ndonohoe 2014-11-14 15:06:29

+0

'Button's'ContentPresenter'正在使用'TemplateBinding'(100%肯定)。我試圖理解你可能會問(如果它不是一個綁定問題),只是不明白;)'DataContext'?它可以設置爲yes,它由'Button'繼承,但它不在'Button'控件模板中使用。所以再一次,你的問題是什麼? – Sinatr 2014-11-14 15:26:00

回答

0

[排序的前面回答的,因爲我不知道我回答什麼問題;)]

這裏是Button控制模板的ContentPresenter(你看到here什麼是公正的一個例子一些可能的模板

<ContentPresenter RecognizesAccessKey="True" 
    Content="{TemplateBinding ContentControl.Content}" 
    ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}" ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}" Margin="{TemplateBinding Control.Padding}" HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" /> 

正如你可以看到它使用TemplateBinding。模板中沒有DataContext。您在不要在模板中使用DataContextBinding