Visible line count of a TextBlock

前端 未结 4 1111
Happy的楠姐
Happy的楠姐 2020-12-16 02:44

If you set TextWrapping to \"Wrap\", a WPF TextBlock can have several lines of text. Is there a \"clean\" way to get the number of lines of text? I considered looking at the

4条回答
  •  星月不相逢
    2020-12-16 03:25

    I have seen that this question is already 7 years old, but I just came with a solution:

    The TextBlock have a private property called LineCount. I created an extension method to read this value:

    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);
        }
    }
    

提交回复
热议问题