在ItemTemplate
内我需要两列,每列50%。提供的文本较长且未包装,但占用的宽度超出预期。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="650">
<ListBox x:Name="ListView">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock TextWrapping="Wrap">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce dapibus commodo dui vulput
</TextBlock>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
要重现样本,您需要在后面的代码中调用:
ListView.ItemsSource = new[] { new object() };
答案 0 :(得分:2)
TextBlock在此设置中接收它想要的所有宽度,如果需要,第二个网格列将离开屏幕。您可以限制内部网格的宽度以强制它仅分配它具有的空间:
<DataTemplate>
<Grid Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock TextWrapping="Wrap">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce dapibus commodo dui vulput
</TextBlock>
</Grid>
</DataTemplate>