2009-08-29 63 views
15

我試圖做這樣的事情......我的WPF樣式設置器可以使用TemplateBinding嗎?

<Style 
    x:Key="MyBorderStyle" 
    TargetType="Border"> 
    <Setter 
     Property="BorderBrush" 
     Value="{StaticResource MyBorderBrush}" /> 
    <Setter 
     Property="Background" 
     Value="{StaticResource MyBackgroundBrush}" /> 
    <Setter 
     Property="Padding" 
     Value="{TemplateBinding Padding}" /> 
</Style> 

...但我得到的錯誤:'Padding' member is not valid because it does not have a qualifying type name.

如何提供一個「合格的類型名」?

注:我試圖做到這一點的原因是,我想在一系列類似的ControlTemplates中包含相同的邊框。

謝謝。

編輯:

嗯,我想這...

<Setter 
    Property="Padding" 
    Value="{TemplateBinding GridViewColumnHeader.Padding}" /> 

...它實際上編譯,但後來當我跑的應用程序,我得到了一個XamlParseException

Cannot convert the value in attribute 'Value' to object of type ''.

我想也許合格PaddingGridViewColumnHeader(這是我想使用這種風格的ControlTemplate)將工作,但沒有骰子。

編輯2:

那麼,根據對TemplateBinding的文檔,它說:

Links the value of a property in a control template to be the value of some other exposed property on the templated control.

所以,它聽起來像什麼,我要做的只是普通不可能的。我真的希望能夠爲控件模板中的某些控件創建可重用的樣式,但我猜這些樣式中不能包含模板綁定。

回答

31

這應該適用於模板化控件並且您希望將該控件的屬性值綁定到模板內的其他控件的屬性的情況。在你的情況下,你是模板化的東西(稱之爲MyControl),並且該模板將包含一個邊界,其Padding應該綁定到MyControl的填充。

MSDN documentation

A TemplateBinding is an optimized form of a Binding for template scenarios, analogous to a Binding constructed with {Binding RelativeSource={RelativeSource TemplatedParent}}.

無論出於何種原因,指定TemplatedParent作爲源的結合似乎並不風格二傳手內工作。爲了解決這個問題,你可以指定相對父對象作爲模板控件的AncestorType(它有效地發現了TemplatedParent提供了你沒有在MyControl模板中嵌入其他MyControls)。

我在嘗試自定義模板的Button控件時,使用了此解決方案,其中Button的(String)內容需要綁定到ControlTemplate中按鈕的TextBlock的Text屬性。以下是代碼的樣子:

<StackPanel> 
    <StackPanel.Resources> 
     <ControlTemplate x:Key="BarButton" TargetType="{x:Type Button}"> 
      <ControlTemplate.Resources> 
       <Style TargetType="TextBlock" x:Key="ButtonLabel"> 
        <Setter Property="Text" Value="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type Button}} }" /> 
       </Style> 
      </ControlTemplate.Resources> 
      <Grid> 
       <!-- Other controls here --> 
       <TextBlock Name="LabelText" Style="{StaticResource ButtonLabel}" /> 
      </Grid> 
     </ControlTemplate> 
    </StackPanel.Resources> 
    <Button Width="100" Content="Label Text Here" Template="{StaticResource BarButton}" /> 
</StackPanel> 
+0

好主意,Shane。謝謝。 – devuxer 2010-06-22 20:54:47

3

屬性可以通過在類型名稱前加上前綴來限定。例如,Border.Padding而不是Padding

但是,我不確定它適合您的情況。在控制模板內部使用TemplateBinding

+1

謝謝,@Kent。你的回答給了我一個嘗試的想法(見上面我的編輯),但它沒有奏效。 「TemplateBinding」只能在ControlTemplate中使用......只要我能說服解析器說我打算只在ControlTemplate中使用這種風格...... – devuxer 2009-08-29 16:19:00

相關問題