Aligning ListBoxItem content
I am trying to align the content of a ListBoxItem
. In the example below I want to have the TextBlock
left aligned and the Button
right aligned in each row of the ListBox. But the Button always follows directly after the end of the TextBlock's text and isn't right aligned in the ListBox.
<StackPanel>
<ListBox ItemsSource="{Binding MyDataList}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
开发者_C百科 <TextBlock Text="{Binding SomeTextProperty}"
VerticalAlignment="Center" Margin="5" />
<Button Content="Display"
HorizontalAlignment="Right" Margin="5"
Command="{Binding SomeCommand}"
CommandParameter="{Binding}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
Something needs to be changed in my XAML, I guess. What am I doing wrong?
Thanks for help!
You'll need a different panel type, but you'll also need to get the content to stretch across the ListBox. You can either specify it as a ControlTemplate for the ListBoxItem, or use the DataTemplate and set ListBox HorizontalContentAlignment to stretch (+1 to Dan Bryant in his comment under the question for pointing this out).
<ListBox>
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid>
<TextBlock Text="{Binding SomeTextProperty}" VerticalAlignment="Center" Margin="5"/>
<Button Content="Display" HorizontalAlignment="Right" Margin="5"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
or
<ListBox HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<TextBlock Text="{Binding SomeTextProperty}" VerticalAlignment="Center" Margin="5"/>
<Button Content="Display" HorizontalAlignment="Right" Margin="5"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Try using an other panel instead of a stackpanel.. Grid or dock should do the job pretty nice.
Just replace your Grid Width with whatever value :
<ListBox ItemsSource="{Binding MyDataList}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="150">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{Binding BusinessProperty}"
VerticalAlignment="Center"
Margin="5" />
<Button Grid.Column="1"
Content="Display"
HorizontalAlignment="Right" Margin="5" Command="{Binding SomeCommand}" CommandParameter="{Binding}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The texblock and the button are going to take just the place they need and the middle grid column will fill the remaining space, "pushing" first and last column to the left and to the right respectively in the amount of space provided by the grid (here 150px)
精彩评论