TextBlock的可见行数

时间:2009-07-09 19:27:58

标签: wpf wpf-controls textblock

如果将TextWrapping设置为“Wrap”,则WPF TextBlock可以包含多行文本。 是否有“干净”的方式来获取文本行数?我考虑查看所需的高度并将其除以每条线的估计高度。但是,这看起来很脏。还有更好的方法吗?

4 个答案:

答案 0 :(得分:8)

关于WPF的一件事非常好,因为所有控件都是非常不露面的。因此,我们可以使用TextBox,它具有LineCount属性(为什么它不是DependencyProperty或为什么TextBlock也不具备它我不知道)。使用TextBox,我们可以简单地重新模板化它,使其行为和看起来更像TextBlock。在我们的自定义样式/模板中,我们将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,但我们如何获得行数?

好吧,如果我们想直接在后面的代码中访问它,那么我们可以注册到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来做同样的事情,但现在我们可以在任何地方使用任何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>

答案 1 :(得分: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;
                }
            }
        }

答案 2 :(得分:1)

我已经看到这个问题已经有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 :(得分:-2)

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

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