如何最好地将WPF ListBox.ItemTemplate的内容拉伸到ListBoxItem的宽度?

3
我知道这可能是重复的,但我还没有找到最好的解决方案。我碰到了使用ListBox.ItemTemplate的问题,我希望内容Grid的HorizontalAlignment属性为“Stretch”(不起作用)。所以我尝试将Grid的宽度绑定到ListBoxItem上,但最后一个条目的行为很奇怪。如果绑定到ListBox的宽度,会出现滚动条,尽管转换器可以解决这个问题,但我认为必须有更简单和优雅的解决方案。
代码如下:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new List<Data>()
        {
            new Data("a1","a2"),
            new Data("b1","b2"),
            new Data("c1","c2")
        };
    }
        public class Data
        {
            public Data(string s1, string s2)
            {
                this.S1 = s1;
                this.S2 = s2;
            }
            public string S1 { get; set; }
            public string S2 { get; set; }
        }
    }

Xaml:

<Grid>
    <ListBox ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Background="Blue" 
                      Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, 
                    Path=ActualWidth, Mode=OneWay}"
                      >
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding S1, Mode=OneWay}" 
                               FontSize="20" Grid.Column="0"/>
                    <TextBlock Text="{Binding S2, Mode=OneWay}" 
                               FontSize="20" Grid.Column="1"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

enter image description here enter image description here enter image description here

1个回答

7

尝试将ListBoxItemHorizontalContentAlignment设置为Stretch,例如:

<ListBox ItemsSource="{Binding}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接