Skip to main content
 首页 » 编程设计

c#之CharacterEllipsis 在 ItemsControl WPF 中不起作用

2024年02月06日11tintown

我试图在 ItemsControl 的 DataTemplate 内的文本上设置 CharacterEllipsis。

<Window x:Class="CustomPanel.Window1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="clr-namespace:CustomPanel;assembly=" 
Title="Window1" Height="400" Width="400"> 
<Window.Resources> 
    <Style TargetType="{x:Type TextBlock}"> 
        <Setter Property="TextTrimming" Value="CharacterEllipsis"></Setter> 
    </Style> 
 
    <DataTemplate DataType="{x:Type local:Person}"> 
        <StackPanel Orientation="Horizontal"> 
            <TextBlock Text="{Binding Name}" 
                       Margin="100,0,0,0"/> 
        </StackPanel> 
    </DataTemplate> 
</Window.Resources> 
 
<Grid> 
    <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="*"/> 
    </Grid.ColumnDefinitions> 
 
    <ItemsControl ItemsSource="{Binding Persons}"  
                  Grid.Column="0"> 
    <ItemsControl.ItemsPanel> 
        <ItemsPanelTemplate> 
            <StackPanel /> 
        </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
</ItemsControl> 
 
</Grid> 

我还尝试为 ItemsControl、StackPanel 和 TextBlock 本身设置宽度。

有什么想法吗?

编辑

为了强调这不是 Style 或 StackPanel 的问题,我删除了两者,但它仍然不起作用

<Window.Resources> 
    <DataTemplate DataType="{x:Type local:Person}"> 
            <TextBlock Text="{Binding Name}" 
                       TextTrimming="CharacterEllipsis" 
                       Margin="100,0,0,0" 
                       Width="200"/> 
    </DataTemplate> 
</Window.Resources> 
 
<Grid> 
    <ItemsControl ItemsSource="{Binding Persons}"/> 
</Grid> 

澄清

当文本太大时这非常有效,但我希望它在窗口调整到更小的宽度时也能正常工作。

请您参考如下方法:

DataTemplate 不会从窗口中选取样式,因为它不在该范围内。在 DataTemplate.Resources 或 Application.Resources 中移动样式,以便它可以被 DataTemplate 中的 TextBlock 选取.

其次,您已将 TextBlock 包裹在 StackPanel 中,这使其可以无限扩展。因此,移除包装 TextBlock 的 Stackpanel。

第三,ItemsControl的约束宽度或者MaxWidth自己设置。

<Window.Resources> 
    <DataTemplate DataType="{x:Type local:Person}"> 
        <DataTemplate.Resources> 
            <Style TargetType="{x:Type TextBlock}"> 
                <Setter Property="TextTrimming" Value="CharacterEllipsis"/> 
            </Style> 
        </DataTemplate.Resources> 
        <TextBlock Text="{Binding Name}"/> 
    </DataTemplate> 
</Window.Resources> 
<ItemsControl ItemsSource="{Binding Persons}" Width="30"> 
    <ItemsControl.ItemsPanel> 
        <ItemsPanelTemplate> 
            <StackPanel/> 
        </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
</ItemsControl> 

更新:

如果您想让它用于调整窗口大小,不要设置宽度,而是在 TextBlock 上设置最大宽度:

<Window.Resources> 
    <DataTemplate DataType="{x:Type local:Person}"> 
        <TextBlock Text="{Binding Name}" MaxWidth="200" 
                    TextTrimming="CharacterEllipsis"/> 
    </DataTemplate> 
</Window.Resources> 
<ItemsControl Margin="100,0,0,0" ItemsSource="{Binding Persons}"/>