对齐 ListBoxItem 内容

Sla*_*uma 4 .net wpf listbox

我正在尝试对齐 a 的内容ListBoxItem。在下面的示例中,我希望列表框的每一行TextBlock左对齐和右对齐。Button但 Button 始终紧跟在 TextBlock 文本末尾之后,并且在 ListBox 中不右对齐。

<StackPanel>
    <ListBox ItemsSource="{Binding MyDataList}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <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>
Run Code Online (Sandbox Code Playgroud)

我想我的 XAML 中需要进行一些更改。我究竟做错了什么?

感谢帮助!

Mar*_*iec 6

您将需要不同的面板类型,但您还需要让内容在列表框中伸展。您可以将其指定为 ListBoxItem 的 ControlTemplate,或者使用 DataTemplate 并将 ListBox Horizo​​ntalContentAlignment 设置为拉伸(在问题下的评论中为 Dan Bryant 指出这一点+1)。

<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>
Run Code Online (Sandbox Code Playgroud)

或者

        <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>
Run Code Online (Sandbox Code Playgroud)