代码之家  ›  专栏  ›  技术社区  ›  Vin

如何允许用户在WPF中向UI控件添加注释?

  •  5
  • Vin  · 技术社区  · 16 年前

    The in-built Annotations support for Document based controls is awesome in WPF

    我想知道如何才能将功能添加到WPF常见控件中,如按钮、文本框、列表框项目等。想法是允许用户在UI屏幕上向其他用户传递一些注释。

    首先想到的是从DocumentViewerBase继承并创建自己的自定义控件。我不确定这会是怎样的结果。如果非自定义控件需要注释,该怎么办?

    有没有人看过这种功能?

    1 回复  |  直到 16 年前
        1
  •  5
  •   Bob King    16 年前

    嗯,我可能会用一个 adorner :

    Imports System.Windows
    Imports System.Windows.Documents
    Imports System.Windows.Media
    
    Public Class Annotation
        Inherits Adorner
    
        Private _fill As Brush
        Private _pen As Pen
        Private _text As FormattedText
        Private _annotationText as String
    
        Public Sub New(ByVal adornedElement As UIElement, ByVal annotationText as String)
            MyBase.New(adornedElement)
            _annotationText = annotationText
            _fill = New SolidColorBrush(Color.FromArgb(&H33, &HB0, &HC4, &HDE))
            _fill.Freeze()
            _pen = New Pen(Brushes.LightSteelBlue, 3.0)
            _pen.Freeze()
            _text = New FormattedText(_annotationText, Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, New Typeface("Verdana"), 11.0, Brushes.Black)
            Me.IsHitTestVisible = False
        End Sub
    
        Protected Overrides Sub OnRender(ByVal drawingContext As DrawingContext)
            MyBase.OnRender(drawingContext)
            Dim adornedRect As New Rect(MyBase.AdornedElement.RenderSize)
            drawingContext.DrawRectangle(_fill, _pen, adornedRect)
            drawingContext.DrawText(_text, New Point(0,0))
        End Sub
    
    End Class
    

    然后您可以通过以下方式使用它:

    Private Sub AddAnnotation(ByVal uie As UIElement, ByVal annotationText as String)
        Dim annotation = New Annotation(uie)
        Dim adornerLayer = AdornerLayer.GetAdornerLayer(uie, annotationText)
        adornerLayer.Add(annotation)
    End Sub
    

    我将让您调整注释的位置和实际外观,但您可以理解。这对我有用 UIElement,包括自定义控件。

    这是一个即兴的回答,基于我对装饰师所做的其他工作。上面的代码可以编译,也可以不编译。我没有提供编辑注释的方法,但是您可以通过删除“Me.ishitsetvisible=False”行并在装饰器中处理MouseUp事件来轻松编辑注释。