views:

690

answers:

1

I have a list box which is of a certain fixed width. The number of items in the listbox varies. Is there a way to center the contents of the list box? The "Content Presenter" of the ListBoxItem ,centers each item inside its Template instead of centering it with respect to the entire listbox width.

Sorry about not replying earlier. The issue was with the width of the ItemsPanelTemplate which I was using in my Listbox. Earlier Width was set to 925. Changing this Width to MaxWidth worked. The code:

<ItemsPanelTemplate x:Key="ItemsPanelKey">
        <Contact:AnimatedWrapPanel HorizontalAlignment="Center" MaxWidth="925">
           <Contact:AnimatedWrapPanel.Interpolation>
                <interpolate:BackInterpolation Amplitude=".5" Suppression=".2" EdgeBehavior="5"/>
            </Contact:AnimatedWrapPanel.Interpolation>
        </Contact:AnimatedWrapPanel>

   </ItemsPanelTemplate>
A: 

Not sure, but sounds like what you want is a custom item template that centers each item. If I'm right, the only tricky thing is that the template has to be the same fixed width as the listbox. So if your listbox contains some object Foo and Foo.Text is a simple text property to be displayed, you could do it like so in Xaml:

  <ListBox x:Name="TheListBox" Width="300">
    <ListBox.ItemTemplate>
      <DataTemplate>
        <Grid Width="300">
          <TextBlock Text="{Binding Text}" HorizontalAlignment="Center" />
        </Grid>
      </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>

and the code behind contains something like:

List<Foo> ListOfFoo = new List<Foo>();
ListOfFoo.Add(new Foo(){Text="Something"});
ListOfFoo.Add(new Foo(){Text="Something Else"});
ListOfFoo.Add(new Foo(){Text="Something Completely Different"});

TheListBox.ItemsSource = ListOfFoo;

If it's more complex or you can't make it work, post some code and we'll go from there.

Raumornie
My bad. The items of the list box are arranged horizontally and work fine normally. But I have a wrap panel as the ItemsPanelTemplate. When I don't set the width of this wrap panel, the items of the list are horizontally aligned centrally. However, if I set the width to ensure that if there are more items they wrap over,in case of lesser number of items, the items are aligned to the left. I have set the Horizontal alignment property to center for the wrap panel.
Could you post the xaml you're using?
Raumornie