c# - 将 WPF ListBox.ItemTemplate 的内容拉伸(stretch)到 ListBoxItem 宽度的最佳方法

标签 c# wpf layout listbox datatemplate

我知道这可能是重复的,但我还没有找到最佳解决方案。我只是遇到了使用 ListBox.ItemTemplate 的问题,我希望内容网格为 Horizo​​ntalAlignment="Stretch"(不起作用)。所以我尝试将 Grid' Width 绑定(bind)到 ListBoxItem,但最后一项的行为很奇怪。如果绑定(bind)ListBox的Width,会有滚动条,虽然转换器可以解决,但我想一定有更简单优雅的解决方案。

代码隐藏:

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

最佳答案

尝试将ListBoxItemHorizo​​ntalContentAlignment设置为Strecth,例如:

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

关于c# - 将 WPF ListBox.ItemTemplate 的内容拉伸(stretch)到 ListBoxItem 宽度的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24337798/

相关文章:

c# - 使用 ScaleTransform 和 TranslateTransform 在 WPF 图像控件的显示区域中显示图像的一部分

android - 如何修复布局?

c# - EF Core 查询 - 有没有办法按字母顺序查找下一个和上一个项目?

c# - COM 如何支持可选参数?

c# - 截取桌面 C# (WPF) 屏幕截图时出现延迟

c# - 过滤项目来源

java - ListView 项目布局问题 - 将 ImageView 与 TextView 组合

android - 在 strings.xml 中存储十六进制颜色值

c# - 转换字符串 Ex : "Friday, 11 of november of 2022" to DateTime C#

c# - 在 C# 中手动信任 SSL 证书