Search code examples
windows-phone-7silverlight-4.0

Button width relative to its contentpresenters width


Hi i have a style for a button that retemplates the style like this

<Style x:Name="NoStyleButton" TargetType="Button">    
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                    <ContentPresenter  x:Name="ContentPresenterInButton"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

The problem is that i want the width of the button to be the same as the content inside the button. If i put a button with this style in a stackpanel the buttons width gets the same as the stackpanel, wich causes a problem when there is little content inside the button (Think small TextBlock), the user can press the button even if they click besides the TextBlock inside the button.

I thought you could do something similar to

<Setter Property="Width" Value="{Binding ActualWidth, ElementName=ContentPresenterInButton}"/>

But that doesnt work.

Any thoughts?


Solution

  • The problem is that it is the StackPanel which dictates your Button width, not the content. You can set the buttons horizontal alignment so that it does not stretch to fill the available width:

    <StackPanel Orientation="Vertical">
      <Button HorizontalAlignment="Left">foo</Button>
      <Button>bar</Button>
    </StackPanel>
    

    enter image description here