【问题标题】:Best way to stretch WPF ListBox.ItemTemplate's contents to the width of ListBoxItem将 WPF ListBox.ItemTemplate 的内容拉伸到 ListBoxItem 宽度的最佳方法
【发布时间】:2014-06-21 11:24:17
【问题描述】:

我知道这可能是重复的,但我还没有找到最佳解决方案。我只是遇到了使用 ListBox.ItemTemplate 的问题,我希望内容网格为 Horizo​​ntalAlignment="Stretch"(不起作用)。所以我尝试将 Grid 的 Width 绑定到 ListBoxItem,但最后一项的行为很奇怪。如果绑定到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>

【问题讨论】:

    标签: c# wpf layout listbox datatemplate


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-22
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-18
      • 2015-12-07
      • 2017-02-14
      相关资源
      最近更新 更多