views:

134

answers:

1

Hi,

General question. I have a ControlTemplate that is reasonably complex. Several TextBoxes etc. I can't use TemplateBinding to bring all the properties to the surface so that I can set all the styles.

Is there a way for a Style to 'delv' into the controls within a control to set values?

Hope my question is clear without an example.

Thanks

A: 

The short answer is no. The ControlTemplate is essentially a black box, at least where XAML is concerned (there are ways to dig down the visual tree in code).

When you say you "can't use TemplateBinding", why not? If you just don't have enough available properties that can be fixed by creating some attached properties for the values you want to pass through. This is assuming you're templating a control that you can't change, otherwise you can just add new dependency properties.

Attached property:

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

And usage in Style and Template:

<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>

Using this method also still allows overriding values on individual instances.

John Bowen
Hi John .. thanks .. I have been using DependancyProperties in a Custom Control .. but Attached Properties are a good alternative for me.. I'm an experienced developer on a fasttrack WPF 'experience' and was just checking I now of all the alternative ways of solving my problem.I score your answer 10/10 for clarity and concisness..thanks
Adam