Best way to stretch WPF ListBox.ItemTemplate's contents to the width of ListBoxItem

ぐ巨炮叔叔 提交于 2019-12-07 16:41:05

问题


I know this may be duplicate, but I haven't found a best solution. I simply come across a issue of using ListBox.ItemTemplate, I want the content Grid to HorizontalAlignment="Stretch"(not work). So I tried to bind the Grid' Width to the ListBoxItem, but the last item behaves strangely. If bind to the Width of ListBox, there will be a scrollbar, although a converter may solve it, I think there must be some more simple and elegant solution.

Codebehind:

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>


回答1:


Try to set ListBoxItem's HorizontalContentAlignment to Strecth, for example :

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


来源:https://stackoverflow.com/questions/24337798/best-way-to-stretch-wpf-listbox-itemtemplates-contents-to-the-width-of-listboxi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!