namespace PCL.Core.Utils.Exts; using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; /// /// 提供 WPF UI 控件的扩展方法。 /// public static class UiExtension { /// /// 检查控件是否在指定窗口的可视区域内,且控件本身可见。 /// /// 要检查的 FrameworkElement。 /// 主窗口,用于确定可视区域。 /// 如果控件部分或完全在窗口可视区域内且可见,则返回 true;否则返回 false。 /// 为 null 时抛出。 public static bool IsVisibleInWindow(this FrameworkElement element, Window mainWindow) { if (!element.IsVisible) return false; try { var transform = element.TransformToAncestor(mainWindow); var bounds = transform.TransformBounds(new Rect(0, 0, element.ActualWidth, element.ActualHeight)); var windowRect = new Rect(0, 0, mainWindow.ActualWidth, mainWindow.ActualHeight); return windowRect.IntersectsWith(bounds); } catch (InvalidOperationException) { return false; } } /// /// 检查 TextBlock 是否因 TextTrimming 属性导致文本被截断。 /// /// 要检查的 TextBlock。 /// 如果文本被截断,则返回 true;否则返回 false。 /// 为 null 时抛出。 public static bool IsTextTrimmed(this TextBlock textBlock) { if (textBlock.TextTrimming == TextTrimming.None) return false; try { var formattedText = new FormattedText( textBlock.Text, System.Globalization.CultureInfo.CurrentCulture, textBlock.FlowDirection, new Typeface(textBlock.FontFamily, textBlock.FontStyle, textBlock.FontWeight, textBlock.FontStretch), textBlock.FontSize, textBlock.Foreground, VisualTreeHelper.GetDpi(textBlock).PixelsPerDip ); return formattedText.Width > textBlock.ActualWidth; } catch (Exception) { return false; } } }