tags:

views:

24

answers:

1

My ListBox is databound to 2 fields. The first is left aligned which is fine, the problem is with the second one which has to be right aligned. I tried using TextAlignment ="Right" and also HorizontalAlignment="Right", none of them worked.

Here is a sample code:

<ListBox x:Name="_listBox"> 
 <ListBox.DataTemplate>
       <DataTemplate>
           <StackPanel Orientation="Horizontal" Margin="0,4,8,0">
                 <TextBlock Text="{Binding Path=ContainerNumber}" />
                 <TextBlock TextAlignment="Right" Text="{Binding Path=Content}"/>
           </StackPanel>
        </DataTemplate>
 </ListBox.DataTemplate>

Any ideas?

A: 

Add to the StackPanel markup:

<StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,4,8,0">

This problem is that the StackPanel isn't using all the width available because it is by default aligned Left horizontally.

EDIT: Alternatively you need to style ListBoxItems:

<ListBox.Resources>
    <Style x:Key="{x:Type ListBoxItem}" TargetType="{x:Type ListBoxItem}">
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="HorizontalAlignment" Value="Stretch"/>
    </Style>
</ListBox.Resources>

Hope this helps.

Goblin
Thanks for the reply. HorizontalAlignment="Stretch" didnot work and actually the default value is stretch for both horizontal and vertical alignments. http://msdn.microsoft.com/en-us/library/system.windows.controls.stackpanel.aspx
My mistake - only suggestion left is to try the above style.
Goblin
It did work. Thanks. The only bug I see now was the default alternating background(light gray for alternating elements in listbox) is not working when inserted the style. Meanwhile I figured setting HorizontalContentAlignment="Stretch" on listbox did the job. Thanks so much.