0

I have a combobox defined in xaml:

<ComboBox Width="100"/>

This ComboBox, along with all other combobxes I have, is styled with a ControlTemplate which I copied and edited some colors and such in it.

<ControlTemplate TargetType="{x:Type ComboBox}">....

In this control template, how can I access the value of the Width attribute from the element above?

So for example:

<ControlTemplate TargetType="{x:Type ComboBox}">
     <Grid Width="??{Binding WidthValue}??" >....

Where the {Binding WidthValue} is 100, from the Width="100" above.

user3595338
  • 737
  • 3
  • 11
  • 26

2 Answers2

1
<Grid Width="{TemplateBinding Width}">

P.S. you'll often see this used in the default control templates for controls for attributes like Padding, Margin, and SnapsToDevicePixels

Daniel Ward
  • 274
  • 2
  • 12
0

You can use TemplatedParent binding

<Grid Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Width}">

but you shouldn't need to as Grid should stretch so if you limit ComboBox to 100 you should automatically limit Grid inside

EDIT

If you need to bind to width then I would suggest to bind to ActualWidth instead of Width

<Grid Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ActualWidth}">

as Width does not need to be defined in all controls where this template is used

dkozl
  • 32,814
  • 8
  • 87
  • 89
  • I went with the shorter solution above and used Width="{TemplateBinding ActualWidth}" and it works exactly like I wanted, thanks. What is the difference between the short one and the longer one anyway? – user3595338 Jun 10 '14 at 16:30
  • check [this](http://stackoverflow.com/questions/1131222/wpf-templatebinding-vs-relativesource-templatedparent) question – dkozl Jun 10 '14 at 16:31