将WPF ListBox.ItemTemplate的内容拉伸到ListBoxItem的宽度的最佳方法 [英] Best way to stretch WPF ListBox.ItemTemplate's contents to the width of ListBoxItem

查看:865
本文介绍了将WPF ListBox.ItemTemplate的内容拉伸到ListBoxItem的宽度的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这可能是重复的,但是我没有找到最佳解决方案.我只是遇到了使用ListBox.ItemTemplate的问题,我希望内容Grid为Horizo​​ntalAlignment =" Stretch "(不起作用).因此,我尝试将Grid的Width绑定到 ListBoxItem ,但是最后一项的行为异常.如果绑定到 ListBox 的Width,将有一个滚动条,尽管转换器可以解决它,但我认为必须有一些更简单,更优雅的解决方案.

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.

隐藏代码:

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>

推荐答案

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

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>

这篇关于将WPF ListBox.ItemTemplate的内容拉伸到ListBoxItem的宽度的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆