How to subtract offset (like 10 pixels) from width of stack panel where width is databound


  • I have a custom control whose width I get from the parent through databinding.  I'm getting scrollbars because the control ends up a little too wide.


    How can I subtrack a number of pixels from the width automatically?  It's currently databound from the parent window.


    Code Snippet

            Width="{Binding Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=MyWidth}"  Height="auto"  >



    And it is set in the parent with this:


    Code Snippet
    <ObjectDataProvider x:Key="SessionsODSDS" MethodName="GetAllSessions" d:IsDataSource="True" ObjectType="{x:Type WPF07:SessionsODS}"/>
      <DataTemplate x:Key="SessionsODSTemplate">
       <WPF07:SessionView MyWidth="{Binding Path=ActualWidth, ElementName=DockPanel, Mode=OneWay}"




    Tuesday, September 11, 2007 1:51 PM

All replies

  • If you just want the control to fill all the available width provided by it's host, you shouldn't set any width at all on the control. Instead you should set the HorizontalContentAlignment of the parent control to Stretch. That way the parent control's layout logic will automatically size the contained control to the available space on your behalf.



    Tuesday, September 11, 2007 2:58 PM
  • Hi Lester and thanks,


    Not too long ago I got accused of answering posts with one liners by a forum member on another forum.  But, when the one liner is EXACTLY what I needed, I got to love those one liners.


    BTW, for future readers, I could not use auto and stretch because I'm bundling a listbox inside a custom control which is inside a parent control and the listbox would not respect the parent's size.  I needed to bind the listbox's width to a dependencyproperty I passed into the usercontrol which is the size of the parent control (phew, that was a mouthful).


    Because I was passing the depenencyproperty in as a string (to width), I needed to add to the ArithmaticConverter class the following code.


    Code Snippet

    object value = null;

    if (valueIn is String)


    value = Convert.ToDouble(valueIn);




    value = valueIn;




    Wednesday, September 12, 2007 12:16 AM