tags:

views:

531

answers:

3

Is there a way to have XAML properties scale along with the size of the uielements they belong to?

In essence, I have a control template that I have created too large for it's use/ mainly because I want to use the same control with different sizes. The problem is that I can set the control size to Auto (in the ControlTemplate), however the properties of the intrisic template elements aren't resized: eg StrokeThickness remains at 10 while it should become 1.

It works fine when I apply a ScaleTransform on the template, but that results in a control that's too small when it's actually used: the width/height=Auto resizes the control to the proper size and then the scaletransform is applied. So I'm stuff with a sort of nonscalable control.

I'm a bit new to WPF, so there might be a straightforward way to do this...

A: 

You could try to bind the width and height of the control inside the template to the width and height respectively of the templated control at runtime. Something like:

<Button>
    <Button.Template>
        <ControlTemplate TargetType={x:Type Button}>
            <Border Width="{TemplateBinding Property=ActualWidth}"
                    Height="{TemplateBinding Property=ActualHeight}">
                <ContentPresenter />
             </Border>
         </ControlTemplate>
    </Button.Template>
</Button>

Note that the binding sources are the FrameworkElement.ActualWidth and FrameworkElement.ActualHeight properties of the templated control. These properties contain the width and height of a control after it has been rendered, which can be different from what has been specified in the Width and Height properties. This is because the values are ultimately calculated at runtime taking into account the size of any parent controls in the visual tree.

Enrico Campidoglio
+4  A: 

Your description is a bit vague, but it sounds like you'll want to have a ViewBox with the Stretch set to Uniform as the root element of your control.

David Mitchell
A: 

Too bad you can't create a control template for a StackPanel, DockPanel, Grid, or any other container.