[英]Best way to stretch WPF ListBox.ItemTemplate's contents to the width of ListBoxItem
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). 我只是遇到了使用ListBox.ItemTemplate的问题,我希望内容Grid为HorizontalAlignment =“ Stretch ”(不起作用)。 So I tried to bind the Grid' Width to the ListBoxItem , but the last item behaves strangely. 所以我尝试将Grid的宽度绑定到ListBoxItem ,但最后一项表现奇怪。 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. 如果绑定到ListBox的宽度,会有一个滚动条,虽然转换器可以解决它,我认为必须有一些更简单和优雅的解决方案。
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: 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>
Try to set ListBoxItem
's HorizontalContentAlignment
to Strecth
, for example : 尝试将ListBoxItem
的HorizontalContentAlignment
设置为Strecth
,例如:
<ListBox ItemsSource="{Binding}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.