windows-8.1 – Windows应用程序确定TextBlock是否被修剪

我有一个具有固定高度/宽度的GridItem.

它包含一个具有最大行集的文本块.

如何确定此文本是否已修剪?
我想添加特殊功能,如果它被修剪.

方法 – 当textwrapping设置为None时

要知道是否修剪了TextBlock,我们可以订阅它的SizeChanged事件并将其ActualWidth与您指定的MaxWidth进行比较.要获得TextBlock的正确ActualWidth,我们需要将TextTrimming保留为其认值(即TextTrimming.None),并在宽度超过时将其设置为trimmed.

方法 – 当textwrapping设置为Wrap时

现在我知道因为textwrapping设置为Wrap并假设未指定VirticalAlignment(认为Stretch),Width将始终保持不变.当TextBlock的实际高度超过其父级的高度时,我们只需要监视SizeChanged事件.

让我们使用一个行为来封装上面的所有逻辑.这里需要提到的是,带有一堆附加属性的静态助手类或从TextBlock继承的新控件可以完全相同;但作为一个大混合粉丝,我更喜欢尽可能使用行为.

行为

public class TextBlockAutoTrimBehavior : DependencyObject,IBehavior
{
    public bool IsTrimmed
    {
        get { return (bool)GetValue(IsTrimmedProperty); }
        set { SetValue(IsTrimmedProperty,value); }
    }

    public static readonly DependencyProperty IsTrimmedProperty =
        DependencyProperty.Register("IsTrimmed",typeof(bool),typeof(TextBlockAutoTrimBehavior),new PropertyMetadata(false));

    public DependencyObject Associatedobject { get; set; }

    public void Attach(DependencyObject associatedobject)
    {
        this.Associatedobject = associatedobject;
        var textBlock = (TextBlock)this.Associatedobject;

        // subscribe to the SizeChanged event so we will kNow when the Width of the TextBlock goes over the MaxWidth
        textBlock.SizeChanged += TextBlock_SizeChanged;
    }

    private void TextBlock_SizeChanged(object sender,SizeChangedEventArgs e)
    {
        // ignore the first time height change
        if (e.PrevIoUsSize.Height != 0)
        {
            var textBlock = (TextBlock)sender;

            // notify the IsTrimmed dp so your viewmodel property will be notified via data binding
            this.IsTrimmed = true;
            // unsubscribe the event as we don't need it anymore
            textBlock.SizeChanged -= TextBlock_SizeChanged;

            // then we trim the TextBlock
            textBlock.TextTrimming = TextTrimming.WordEllipsis;
        }
    }

    public void Detach()
    {
        var textBlock = (TextBlock)this.Associatedobject;
        textBlock.SizeChanged += TextBlock_SizeChanged;
    }
}

XAML

<Grid HorizontalAlignment="Center" Height="73" VerticalAlignment="Center" Width="200" Background="#FFD2A6A6" Margin="628,329,538,366">
    <TextBlock x:Name="MyTextBlock" textwrapping="Wrap" Text="test" FontSize="29.333">
        <Interactivity:Interaction.Behaviors>
            <local:TextBlockAutoTrimBehavior IsTrimmed="{Binding IsTrimmedInVm}" />
        </Interactivity:Interaction.Behaviors>
    </TextBlock>
</Grid>

请注意,行为公开了依赖项属性IsTrimmed,您可以将数据绑定到viewmodel中的属性(在本例中为IsTrimmedInVm).

附:在WinRT中没有FormattedText函数,否则实现可能会有所不同.

相关文章

Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...
Windows文件操作基础代码 Windows下对文件进行操作使用的一段...
Winpcap基础代码 使用Winpcap进行网络数据的截获和发送都需要...
使用vbs脚本进行批量编码转换 最近需要使用SourceInsight查看...