TextBlock的可视行数(Visible line count of a TextBlock)

2019-06-25 12:34发布

如果设置TextWrapping“包装”,一个WPF的TextBlock可以有几行文字。 是否有一个“干净”的方式来获得文本行数? 我认为在寻找所需的高度,并通过在每行的估计高度除以。 然而,这似乎挺脏的。 有没有更好的办法?

Answer 1:

有关WPF有一件事情是非常好的是,所有的控制都非常无外观。 正因为如此,我们可以利用文本框 ,其中有一个LineCount属性(为什么这不是一个DependencyProperty或者为什么TextBlock的不也有它,我不知道)。 与文本框,我们可以简单地重新模板,这样它的行为,看起来更像是一个TextBlock。 在我们的自定义样式/模板,我们要的IsEnabled设为False,只是创建控件的基本重新模板,使残疾人的外观不再存在。 我们还可以结合我们要保持任何属性,如背景,通过使用TemplateBindings的。

<Style x:Key="Local_TextBox"
    TargetType="{x:Type TextBoxBase}">
    <Setter Property="IsEnabled"
            Value="False" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBoxBase}">
                <Border Name="Border"
                    Background="{TemplateBinding Background}">
                    <ScrollViewer x:Name="PART_ContentHost" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
</Setter>
</Style>

现在,会照顾使我们的文本框的外观和行为像一个TextBlock,但我们怎样才能行计数?

那么,如果我们想直接访问它后面的代码,然后我们可以注册到TextBox的SizeChanged事件。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        LongText = "This is a long line that has lots of text in it.  Because it is a long line, if a TextBlock's TextWrapping property is set to wrap then the text will wrap onto new lines. However, we can also use wrapping on a TextBox, that has some diffrent properties availible and then re-template it to look just like a TextBlock!";

        uiTextBox.SizeChanged += new SizeChangedEventHandler(uiTextBox_SizeChanged);

        this.DataContext = this;
    }

    void uiTextBox_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        Lines = uiTextBox.LineCount;
    }

    public string LongText { get; set; }

    public int Lines
    {
        get { return (int)GetValue(LinesProperty); }
        set { SetValue(LinesProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Lines.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty LinesProperty =
        DependencyProperty.Register("Lines", typeof(int), typeof(MainWindow), new UIPropertyMetadata(-1));
}

然而,因为我往往需要在其他地方用那样的属性,那么当前窗口,和/或正在使用MVVM,不希望采取这种办法,那么我们可以创造一些AttachedProperties处理的检索和设置LineCount。 我们将使用AttachedProperties做同样的事情,但现在我们就可以用任何文本框通过文本框,而不是窗口的DataContext的任何地方使用它,并与它结合。

public class AttachedProperties
{
    #region BindableLineCount AttachedProperty
    public static int GetBindableLineCount(DependencyObject obj)
    {
        return (int)obj.GetValue(BindableLineCountProperty);
    }

    public static void SetBindableLineCount(DependencyObject obj, int value)
    {
        obj.SetValue(BindableLineCountProperty, value);
    }

    // Using a DependencyProperty as the backing store for BindableLineCount.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty BindableLineCountProperty =
        DependencyProperty.RegisterAttached(
        "BindableLineCount",
        typeof(int),
        typeof(MainWindow),
        new UIPropertyMetadata(-1));

    #endregion // BindableLineCount AttachedProperty

    #region HasBindableLineCount AttachedProperty
    public static bool GetHasBindableLineCount(DependencyObject obj)
    {
        return (bool)obj.GetValue(HasBindableLineCountProperty);
    }

    public static void SetHasBindableLineCount(DependencyObject obj, bool value)
    {
        obj.SetValue(HasBindableLineCountProperty, value);
    }

    // Using a DependencyProperty as the backing store for HasBindableLineCount.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty HasBindableLineCountProperty =
        DependencyProperty.RegisterAttached(
        "HasBindableLineCount",
        typeof(bool),
        typeof(MainWindow),
        new UIPropertyMetadata(
            false,
            new PropertyChangedCallback(OnHasBindableLineCountChanged)));

    private static void OnHasBindableLineCountChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        var textBox = (TextBox)o;
        if ((e.NewValue as bool?) == true)
        {
            textBox.SetValue(BindableLineCountProperty, textBox.LineCount);
            textBox.SizeChanged += new SizeChangedEventHandler(box_SizeChanged);
        }
        else
        {
            textBox.SizeChanged -= new SizeChangedEventHandler(box_SizeChanged);
        }
    }

    static void box_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        var textBox = (TextBox)sender;
        (textBox).SetValue(BindableLineCountProperty, (textBox).LineCount);
    }
    #endregion // HasBindableLineCount AttachedProperty
}

现在,它是简单的找到LineCount:

<StackPanel>
    <TextBox x:Name="uiTextBox"
             TextWrapping="Wrap"
             local:AttachedProperties.HasBindableLineCount="True"
             Text="{Binding LongText}"
             Style="{StaticResource Local_TextBox}" />

    <TextBlock Text="{Binding Lines, StringFormat=Binding through the code behind: {0}}" />
    <TextBlock Text="{Binding ElementName=uiTextBox, Path=(local:AttachedProperties.BindableLineCount), StringFormat=Binding through AttachedProperties: {0}}" />
</StackPanel>


Answer 2:

// this seems to do the job        

<TextBox x:Name="DescriptionTextBox"
                         Grid.Row="03"
                         Grid.RowSpan="3"
                         Grid.Column="01"
                         Width="100"
                         AcceptsReturn="True"
                         MaxLength="100"
                         MaxLines="3"
                         PreviewKeyDown="DescriptionTextBox_PreviewKeyDown"
                         Text="{Binding Path=Description,
                                        Mode=TwoWay,
                                        UpdateSourceTrigger=PropertyChanged}"
                         TextWrapping="Wrap" />



        /// <summary>
        /// we need to limit a multi line textbox at entry time
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void DescriptionTextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            TextBox thisTextBox = sender as TextBox;
            if (thisTextBox != null)
            {
                // only check if we have passed the MaxLines 
                if (thisTextBox.LineCount > thisTextBox.MaxLines)
                {
                    // we are going to discard the last entered character
                    int numChars = thisTextBox.Text.Length;

                    // force the issue
                    thisTextBox.Text = thisTextBox.Text.Substring(0, numChars - 1);

                    // set the cursor back to the last allowable character
                    thisTextBox.SelectionStart = numChars - 1;

                    // disallow the key being passed in
                    e.Handled = true;
                }
            }
        }


Answer 3:

我已经看到,这个问题已经7岁了,但我只是一个解决方案来:

TextBlock的有一个叫做LineCount的私人财产。 我创建了一个扩展方法来读取这个值:

public static class TextBlockExtension
{
    public static int GetLineCount(this TextBlock tb)
    {
        var propertyInfo = GetPrivatePropertyInfo(typeof(TextBlock), "LineCount");
        var result = (int)propertyInfo.GetValue(tb);
        return result;
    }

    private static PropertyInfo GetPrivatePropertyInfo(Type type, string propertyName)
    {
        var props = type.GetProperties(BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.NonPublic);
        return props.FirstOrDefault(propInfo => propInfo.Name == propertyName);
    }
}


Answer 4:

最简单的方法是LineCount财产。 也有一个名为GetLastVisibleLineIndex,让你知道有多少行文本框可以显示(没有滚动条)方法。

如果你想知道当一个行被添加,您可以在TextChanged事件听取和询问有关LineCount属性(你需要拉斯维加斯LineCount保持到一个变量做表的比较)。



文章来源: Visible line count of a TextBlock