一个TextBlock的可见行数

10

如果将TextWrapping设置为“Wrap”,WPF TextBlock可以有几行文本。是否有一种“清洁”的方法来获取文本行数?我考虑查看所需高度并将其除以每行估计高度。但是,这种方法似乎不太好。是否有更好的方法?

如果将TextWrapping属性设置为“Wrap”,则WPF TextBlock可以在多个文本行中显示文本。有没有一种“干净”的方式来获取文本行数?我曾考虑过查看所需高度并将其除以每行大约估计的高度,但这种做法看起来有些不优雅。是否有更好的解决方法?
4个回答

9
WPF中非常好的一点是所有控件都非常无样式。因此,我们可以利用TextBox,它有一个LineCount属性(为什么它不是DependencyProperty或者为什么TextBlock也没有我不知道)。使用TextBox,我们可以简单地重新定义它的模板,使其行为和外观更像TextBlock。在我们自定义的Style/Template中,我们将设置IsEnabled为False,并创建一个基本的重新模板化控件,以消除禁用的外观。我们还可以通过使用TemplateBindings绑定任何想要维护的属性,如Background。
<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>

现在,这将使我们的TextBox看起来和TextBlock一样,并且表现得像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并且不想采用该方法,因此我们可以创建一些附加属性来处理LineCount的检索和设置。我们将使用AttachedProperties来完成相同的任务,但现在我们将能够在任何地方使用它与任何TextBox一起,并通过该TextBox绑定它,而不是Window的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>

这很好。然而,与TextBlock相比,TextBox的限制更多,因为它们具有统一的字体家族/字体大小。结果,计算行数变得容易。另一方面,TextBlock可以具有不同高度的不同内联,这使得事情有点更加困难。 - tom7

3
// 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;
                }
            }
        }

问题是关于 TextBlock 而不是 TextBox。 - jHilscher

2

我看到这个问题已经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);
    }
}

-3

简单的方法是使用LineCount属性。此外,您还有一个名为GetLastVisibleLineIndex的方法,可以让您知道文本框可以显示多少行(不带滚动条)。

如果您想知道何时添加了一行,可以侦听TextChanged事件并询问LineCount属性(您需要将最后一个LineCount保留到变量中以进行比较)。


TextBlock没有LineCount属性,这完全是TextBox的领域。 - Mike Post

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接