views:

670

answers:

1

I have a databound ListBox with a DataTemplate setup. The DataTemplate contains a Grid control with two column widths of Auto and *. I would like this column to always fill the ListBoxItem and never extend past the LisBox control to make the horizontal scrollbar visible.

I am able to bind the MaxWidth to the DataTemplate's grid using:

MaxWidth="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBox}}, Path=ActualWidth}"

Is this the best way to accomplish this?

I also have the ItemContainerStyle setup to the following. The Triggers have been removed to make the code smaller and easier to read.

<Style x:Key="ListBoxItemContainer" TargetType="{x:Type ListBoxItem}">
    <Setter Property="Padding" Value="3"/>
 <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
 <Setter Property="Template">
  <Setter.Value>
   <ControlTemplate TargetType="{x:Type ListBoxItem}">
    <Border x:Name="Border" BorderBrush="{x:Null}" CornerRadius="4" BorderThickness="1" Margin="1">
     <Border x:Name="InnerBorder" BorderBrush="{x:Null}" CornerRadius="4" BorderThickness="1">
      <ContentPresenter x:Name="ContentPresenter" Margin="{TemplateBinding Padding}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"/>
     </Border>
    </Border>
   </ControlTemplate>
  </Setter.Value>
 </Setter>
</Style>
+2  A: 

You want to avoid binding to ActualWidth and ActualHeight when possible for efficiency sake. 90% of the time you are overlooking built in functionality if you find yourself binding to either of these properties (though there are rare exceptions where it makes sense).

To accomplish what you want you simply need to disable the ListBox's horizontal scrollbar like so:

<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled" />

This will limit the horizontal room allotted to each ListBoxItem, thereby allowing the dynamic * columns to be defined as the remaining space.

Tony Borres
Thanks. I was using <Setter Property="MaxWidth" Value="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=ScrollContentPresenter}}"/> within the Style, however disabling the ScrollViewer fixed the issue.
Luke