2010-03-02 66 views
1

一般問題。我有一個相當複雜的ControlTemplate。幾個文本框等 我無法使用TemplateBinding將所有屬性帶到曲面,以便我可以設置所有樣式。控制模板上的WPF設置

是否有一種方法讓'樣式'可以'控制'到控件中的控件中以設置值?

希望我的問題很明顯,沒有一個例子。

謝謝

回答

1

簡短的回答是沒有。 ControlTemplate本質上是一個黑盒子,至少在XAML方面(有許多方法可以在代碼中挖掘可視化樹)。

當你說你「不能使用TemplateBinding」時,爲什麼不呢?如果您沒有足夠的可用屬性,可以通過爲要傳遞的值創建一些附加屬性來解決這些問題。這假設你是模板化一個你不能改變的控件,否則你可以添加新的依賴屬性。

附加屬性:

public static class CustomProps 
{ 
    public static readonly DependencyProperty MyNewBrushProperty = DependencyProperty.RegisterAttached(
     "MyNewBrush", 
     typeof(Brush), 
     typeof(CustomProps), 
     new UIPropertyMetadata(Brushes.Green)); 

    public static Brush GetMyNewBrush(DependencyObject target) 
    { 
     return (Brush)target.GetValue(MyNewBrushProperty); 
    } 

    public static void SetMyNewBrush(DependencyObject target, Brush value) 
    { 
     target.SetValue(MyNewBrushProperty, value); 
    } 
} 

和使用的風格和模板:

<Style TargetType="{x:Type Button}"> 
    <Setter Property="local:CustomProps.MyNewBrush" Value="Red" /> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type Button}"> 
       <Border Background="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(local:CustomProps.MyNewBrush)}"> 
        <ContentPresenter/> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

使用這種方法也仍然允許在單個實例壓倒一切的價值觀。

+0

嗨約翰..謝謝..我一直在自定義控件中使用DependancyProperties ..但附加屬性是一個很好的替代方案..我是一個有經驗的快速開發WPF'經驗',只是檢查我現在解決我的問題的所有替代方法。 爲了清晰和簡潔,我爲你的答案評分爲10/10 ..謝謝 – Adam 2010-03-02 19:29:37