由于不明原因,使用 TextRange 方法出错

Getting an error with TextRange method for unclear reason

我试图在 wpf 的 richtextbox 中突出显示 TextRange,但是我不断收到以下关于无效参数的错误,尽管我非常有信心该参数实际上是正确的。我了解如何阻止程序崩溃,但如果抛出此 ArgumentException,则我的程序不会执行我希望的操作。

下面是 GetAllWordRanges 方法的代码。

private static IEnumerable<TextRange> GetAllWordRanges(FlowDocument document, List<string> keywords)
{
    foreach (string keyword in keywords)
    {
        TextPointer pointer = document.ContentStart;
        while (pointer != null)
        {
            if (pointer.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
            {
                string textRun = pointer.GetTextInRun(LogicalDirection.Forward);
                MatchCollection matches = Regex.Matches(textRun, keyword);
                foreach (Match match in matches)
                {
                    int startIndex = match.Index;
                    int length = match.Length;
                    TextPointer start = pointer.GetPositionAtOffset(startIndex);
                    TextPointer end = start.GetPositionAtOffset(length);
                    yield return new TextRange(start, end);
                }
            }

            pointer = pointer.GetNextContextPosition(LogicalDirection.Forward);
        }
    }
}

异常详细信息:

System.ArgumentException was unhandled
  HResult=-2147024809
  Message='SolidBrush' parameter type is not valid for formatting property 'Background'.
Parameter name: value
  Source=PresentationFramework
  ParamName=value
  StackTrace:
       at System.Windows.Documents.TextRange.ApplyPropertyValue(DependencyProperty formattingProperty, Object value, Boolean applyToParagraphs, PropertyValueAction propertyValueAction)
       at System.Windows.Documents.TextRange.ApplyPropertyValue(DependencyProperty formattingProperty, Object value)
       at EmailCheckerWPF.TextAnalyser.turnTextRed(RichTextBox TextBox, List`1 Keywords) in c:\Users\Luke\Documents\Caimbridge comp\EmailCheckerWPF\TextAnalyser.cs:line 138
       at EmailCheckerWPF.MainWindow.AnalyseButton_Click(Object sender, RoutedEventArgs e) in c:\Users\Luke\Documents\Caimbridge comp\EmailCheckerWPF\MainWindow.xaml.cs:line 50
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
       at System.Windows.Controls.Primitives.ButtonBase.OnClick()
       at System.Windows.Controls.Button.OnClick()
       at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
       at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
       at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
       at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
       at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
       at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
       at System.Windows.Input.InputManager.ProcessStagingArea()
       at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
       at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
       at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
       at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at EmailCheckerWPF.App.Main() in c:\Users\Luke\Documents\Caimbridge comp\EmailCheckerWPF\obj\Debug\App.g.cs:line 0
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

在过去 winforms 糟糕的日子里,我们有用于渲染的 GDI+ 类型 UI。

然后是WPF。这是对桌面应用程序 UI 堆栈的完全重写。随着创建不同版本的 UI 元素(System.Windows.Forms.Window vs System.Windows.Controls.Window),渲染堆栈和相关的 类 也被重写。无论明智与否,许多以前的模式都在这次重写中重现。

Winforms 将保留在框架中,让不明智的人偶然发现并给自己带来恶作剧。由于我们现在有两个(不兼容的)版本的相同模式在框架中共存,我们也可能不幸地陷入神级 WPF 开发人员的陷阱。

最常见的陷阱之一是导入 System.Drawing 命名空间。 WPF 开发人员的等价物实际上是 System.Windows.Media。这两个名称空间都包含许多极其相似但不兼容的类型。如果你不小心(如果你没有得到好的异常消息告诉你你需要的 effing 类型的 effing 命名空间与你实际使用的 mothereffign 类型的命名空间),你会 using错误的命名空间并开始使用 GDI+ 画笔。

注意,WPF 开发人员。确保您始终使用 WPF 堆栈! Winforms 适用于穷人和未受过教育的人。我们现在不想和那些人交往,是吗?