你應該設置TextBlock.MaxWidth
屬性:
<Grid>
<Grid.Resources>
<XmlDataProvider x:Key="xmlData" XPath="/records">
<x:XData>
<records xmlns="">
<entry text="Veeeeeeeeeeeeeeeeeeery looooooooooooooooooooooong text"/>
<entry text="A little bit shorter text" />
<entry text="Normal text"/>
</records>
</x:XData>
</XmlDataProvider>
</Grid.Resources>
<ListBox
ItemsSource="{Binding Source={StaticResource xmlData}, XPath=entry}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock MaxWidth="200" Text="{Binding [email protected]}" TextTrimming="CharacterEllipsis"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
編輯:
爲了達到你的目標,你應該使用MultiValueConverter
並設置寬度各TextBlock
元素:
XAML:
<Window x:Class="WpfListBoxItemTextTrimming.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:WpfListBoxItemTextTrimming">
<Window.Resources>
<local:ListBoxWidthConverter x:Key="listBoxWidthConverter"/>
</Window.Resources>
<Grid>
<Grid.Resources>
<XmlDataProvider x:Key="xmlData" XPath="/records">
<x:XData>
<records xmlns="">
<entry text="Veeeeeeeeeeeeeeeeeeery looooooooooooooooooooooong text"/>
<entry text="A little bit shorter text" />
<entry text="Normal text"/>
</records>
</x:XData>
</XmlDataProvider>
</Grid.Resources>
<ListBox x:Name="LbMBox"
ItemsSource="{Binding Source={StaticResource xmlData}, XPath=entry}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel IsItemsHost="True" Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding [email protected]}" TextTrimming="CharacterEllipsis">
<TextBlock.Width>
<MultiBinding Converter="{StaticResource listBoxWidthConverter}">
<Binding Path="ActualWidth" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollContentPresenter}}" />
<Binding ElementName="LbMBox" Path="Items.Count" />
</MultiBinding>
</TextBlock.Width>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
ListBoxWidthConverter
轉換器:
public class ListBoxWidthConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values != null && values.Length == 2)
{
var actualWidth = System.Convert.ToDouble(values[0]);
var numOfItems = System.Convert.ToInt32(values[1]);
return (actualWidth/numOfItems) - 10;
}
return Binding.DoNothing;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
@kmatyaszek這裏我的解決辦法 – Jamaxack