21

有没有办法将 a 上的文本修剪指定TextBlock为从左侧?

我已经设法完成了三个场景中的两个(第三种是我需要的):

  1. 定期修剪

    <TextBlock 
        VerticalAlignment="Center" 
        Width="80" 
        TextTrimming="WordEllipsis"
        Text="A very long text that requires trimming" />
    
    // Result: "A very long te..."
    
  2. 左修剪

    <TextBlock 
        VerticalAlignment="Center" 
        Width="80" 
        FlowDirection="RightToLeft"
        TextTrimming="WordEllipsis"
        Text="A very long text that requires trimming." />
    
    // Result: "...A very long te"
    
  3. 在看到文本结尾的地方左修剪

    // Desired result: "...uires trimming"
    

有谁知道这是否可能?谢谢。

4

4 回答 4

6

如果您不关心省略号,而只是想在文本被截断时看到文本的结尾而不是开头,则可以将 TextBlock 包装在另一个容器中,并将其 Horizo​​ntalAlignment 设置为 Right。这将像你想要的那样切断它,但没有椭圆。

<Grid>
    <TextBlock Text="Really long text to cutoff." HorizontalAlignment="Right"/>
</Grid>
于 2012-01-23T00:09:49.773 回答
5

您不能开箱即用地执行此操作,但我可以想到两件事可能会奏效:

1) 为 TextBlock 创建一个附加属性,名为 LeftTrimmingText。然后,您将设置此属性而不是 Text 属性。例如

  <TextBlock my:TextBlockHelper.LeftTrimmingText="A very long text that requires trimming." />

附加属性将计算实际可以显示多少个字符,然后相应地设置 TextBlock 的 Text 属性。

2) 创建您自己的包含 TextBlock 的类,并添加您自己的属性来处理所需的逻辑。

我认为第一种选择更容易。

于 2012-01-19T14:20:30.147 回答
4

这种风格可以完成这项工作。诀窍是重新定义标签的控制模板。然后将内容放在剪贴画布内并与画布右侧对齐。内容的最小宽度是画布的宽度,因此如果有足够的空间,内容文本将左对齐,剪切时右对齐。

如果内容的宽度大于画布,则会触发省略号。

<Style x:Key="LeftEllipsesLabelStyle"
       TargetType="{x:Type Label}">
    <Setter Property="Foreground"
            Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
    <Setter Property="Background"
            Value="Transparent" />
    <Setter Property="Padding"
            Value="5" />
    <Setter Property="HorizontalContentAlignment"
            Value="Left" />
    <Setter Property="VerticalContentAlignment"
            Value="Top" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Label}">
                <Grid >
                    <Grid.Resources>
                        <LinearGradientBrush x:Key="HeaderBackgroundOpacityMask" StartPoint="0,0" EndPoint="1,0">
                            <GradientStop Color="Black"  Offset="0"/>
                            <GradientStop Color="Black" Offset="0.5"/>
                            <GradientStop Color="Transparent" Offset="1"/>
                        </LinearGradientBrush>
                    </Grid.Resources>

                    <Canvas x:Name="Canvas" 
                            ClipToBounds="True" 
                            DockPanel.Dock="Top"  
                            Height="{Binding ElementName=Content, Path=ActualHeight}">

                        <Border 
                            BorderBrush="{TemplateBinding BorderBrush}"
                            Canvas.Right="0"
                            Canvas.ZIndex="0"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}"
                            Padding="{TemplateBinding Padding}"
                            MinWidth="{Binding ElementName=Canvas, Path=ActualWidth}"
                            SnapsToDevicePixels="true"
                            x:Name="Content"
                        >
                            <ContentPresenter
                                HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                Content="{Binding RelativeSource={RelativeSource AncestorType=Label}, Path=Content}"
                                RecognizesAccessKey="True"
                                SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                            >
                                <ContentPresenter.Resources>
                                    <Style TargetType="TextBlock">
                                        <Setter Property="FontSize" Value="{Binding FontSize, RelativeSource={RelativeSource AncestorType={x:Type Label}}}"/> 
                                        <Setter Property="FontWeight" Value="{Binding FontWeight, RelativeSource={RelativeSource AncestorType={x:Type Label}}}"/> 
                                        <Setter Property="FontStyle" Value="{Binding FontStyle, RelativeSource={RelativeSource AncestorType={x:Type Label}}}"/> 
                                        <Setter Property="FontFamily" Value="{Binding FontFamily, RelativeSource={RelativeSource AncestorType={x:Type Label}}}"/> 
                                    </Style>
                                </ContentPresenter.Resources>

                            </ContentPresenter>
                        </Border>
                        <Label 
                            x:Name="Ellipses" 
                            Canvas.Left="0" 
                            Canvas.ZIndex="10"
                            FontWeight="{TemplateBinding FontWeight}"
                            FontSize="{TemplateBinding FontSize}"
                            FontFamily="{TemplateBinding FontFamily}"
                            FontStyle="{TemplateBinding FontStyle}"
                            VerticalContentAlignment="Center" 
                            OpacityMask="{StaticResource HeaderBackgroundOpacityMask}" 
                            Background="{TemplateBinding Background}"
                            Foreground="RoyalBlue"
                            Height="{Binding ElementName=Content, Path=ActualHeight}" 
                            Content="...&#160;&#160;&#160;">
                            <Label.Resources>
                                <Style TargetType="Label">
                                    <Style.Triggers>
                                        <DataTrigger Value="true">
                                            <DataTrigger.Binding>
                                                <MultiBinding Converter="{StaticResource GteConverter}">
                                                    <Binding ElementName="Canvas" Path="ActualWidth"/>
                                                    <Binding ElementName="Content" Path="ActualWidth"/>
                                                </MultiBinding>
                                            </DataTrigger.Binding>
                                            <Setter Property="Visibility" Value="Hidden"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </Label.Resources>

                        </Label>
                    </Canvas>

                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled"
                             Value="false">
                        <Setter Property="Foreground"
                                Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

这里有几个实用程序类

Gte转换器

<c:GteConverter x:Key="GteConverter"/>

这是

public class RelationalValueConverter : IMultiValueConverter
{
    public enum RelationsEnum
    {
        Gt,Lt,Gte,Lte,Eq,Neq
    }

    public RelationsEnum Relations { get; protected set; }

    public RelationalValueConverter(RelationsEnum relations)
    {
        Relations = relations;
    }

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if(values.Length!=2)
            throw new ArgumentException(@"Must have two parameters", "values");

        var v0 = values[0] as IComparable;
        var v1 = values[1] as IComparable;

        if(v0==null || v1==null)
            throw new ArgumentException(@"Must arguments must be IComparible", "values");

        var r = v0.CompareTo(v1);

        switch (Relations)
        {
            case RelationsEnum.Gt:
                return r > 0;
                break;
            case RelationsEnum.Lt:
                return r < 0;
                break;
            case RelationsEnum.Gte:
                return r >= 0;
                break;
            case RelationsEnum.Lte:
                return r <= 0;
                break;
            case RelationsEnum.Eq:
                return r == 0;
                break;
            case RelationsEnum.Neq:
                return r != 0;
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public class GtConverter : RelationalValueConverter
{
    public GtConverter() : base(RelationsEnum.Gt) { }
}
public class GteConverter : RelationalValueConverter
{
    public GteConverter() : base(RelationsEnum.Gte) { }
}
public class LtConverter : RelationalValueConverter
{
    public LtConverter() : base(RelationsEnum.Lt) { }
}
public class LteConverter : RelationalValueConverter
{
    public LteConverter() : base(RelationsEnum.Lte) { }
}
public class EqConverter : RelationalValueConverter
{
    public EqConverter() : base(RelationsEnum.Eq) { }
}
public class NeqConverter : RelationalValueConverter
{
    public NeqConverter() : base(RelationsEnum.Neq) { }
}

这是它的工作。

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

于 2015-06-09T11:45:51.130 回答
0

我不知道这是否是一个错字,但是您在full stop“期望的结果”末尾缺少 。我假设你不想要它。由于您知道应该显示多少个字符,您可以只获取整个字符串的子字符串并显示它。例如,

string origText = "A very long text that requires trimming.";

//15 because the first three characters are replaced
const int MAXCHARACTERS = 15;

//MAXCHARACTERS - 1 because you don't want the full stop
string sub = origText.SubString(origText.Length-MAXCHARACTERS, MAXCHARACTERS-1);

string finalString = "..." + sub;
textBlock.Text = finalString;

如果您不知道您需要多少个字符,那么您可以执行计算来确定它。在您的示例中,80结果为17字符的宽度,如果宽度发生变化,您可以使用该比率。

于 2012-01-19T14:29:26.410 回答