wpf 如何7步寫一個badge控制元件

BearHan發表於2024-08-12

首先看一下效果:

任意控制元件可以附加一個文字在控制元件的右上角,並帶有紅色背景

第一步,新建一個空的wpf專案:

第二步,建立一個類,取名為badge:

第三步,將badge的父類設定成 System.Windows.Documents.Adorner

    public class Badge : Adorner
    {
        public Badge(UIElement adornedElement) : base(adornedElement)
        {

        }
    }

裡面的adornedElement表示badge後面附加的物件

關於Adorner這個類的說明,微軟給了相應的教程 https://learn.microsoft.com/zh-cn/dotnet/desktop/wpf/controls/adorners-overview?view=netframeworkdesktop-4.8

也可以F11檢視Adorner類的說明.

第4步,給badge新增一個Content的附加屬性:

        public static readonly DependencyProperty ContentProperty;

        static Badge()
        {
            ContentProperty = DependencyProperty.RegisterAttached("Content", typeof(string), typeof(Badge),
                new FrameworkPropertyMetadata(string.Empty, new PropertyChangedCallback(ContentChangedCallBack)));
        }

      public static string GetContent(DependencyObject obj)
      {
          return (string)obj.GetValue(ContentProperty);
      }


      public static void SetContent(DependencyObject obj, string value)
      {
          obj.SetValue(ContentProperty, value);
      }

第5步,實現content的回撥方法:

private static void ContentChangedCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var target = d as FrameworkElement;
    if (target != null)
    {
        if (target.IsLoaded)
        {
            var layer = AdornerLayer.GetAdornerLayer(target);
            if (layer != null)
            {
                var Adorners = layer.GetAdorners(target);
                if (Adorners != null)
                {
                    foreach (var adorner in Adorners)
                    {
                        if (adorner is Badge)
                        {
                            layer.Remove(adorner);
                        }
                    }
                }
                layer.Add(new Badge(target));
            }
        }
        else
        {
            target.Loaded += (sender, ae) =>
            {
                var layer = AdornerLayer.GetAdornerLayer(target);
                if (layer != null)
                {
                    var Adorners = layer.GetAdorners(target);
                    if (Adorners != null)
                    {
                        foreach (var adorner in Adorners)
                        {
                            if (adorner is Badge)
                            {
                                layer.Remove(adorner);
                            }
                        }
                    }
                    layer.Add(new Badge(target));
                }
            };
        }
    }
}

第6步,重寫一下OnRender方法:

        protected override void OnRender(DrawingContext drawingContext)
        {
            var element = this.AdornedElement as FrameworkElement;
            Rect adornedElementRect = new Rect(element.DesiredSize);
            var point = adornedElementRect.TopRight;
            point.X = adornedElementRect.Right - element.Margin.Left - element.Margin.Right;

            SolidColorBrush renderBrush = new SolidColorBrush(Colors.Red);
            Pen renderPen = new Pen(new SolidColorBrush(Colors.Red), 0.5);
            double renderRadius = 5;

            var content = this.AdornedElement.GetValue(Badge.ContentProperty).ToString();
            FormattedText formattedText = new FormattedText(content, CultureInfo.GetCultureInfo("zh-cn"), FlowDirection.LeftToRight, new Typeface("Verdana"), 10, Brushes.White);
            var textWidth = formattedText.Width;
            var textHeight = formattedText.Height;
            var rectangleSizeWidth = textWidth < 15 ? 15 : textWidth;
            var rectangleSizeHeight = textHeight < 15 ? 15 : textHeight;
            var size = new Size(rectangleSizeWidth, rectangleSizeHeight);
            Rect rect = new Rect(new Point(point.X - rectangleSizeWidth / 2, point.Y - rectangleSizeHeight / 2), size);

            drawingContext.DrawRoundedRectangle(renderBrush, renderPen, rect, renderRadius, renderRadius);
            drawingContext.DrawText(formattedText, new Point(point.X - textWidth / 2, point.Y - textHeight / 2));
        }

這段程式碼就是在目標控制元件的右上角繪製一個帶圓角的rectangle,背景色為紅色,再繪製一個文字用來顯示content.

第7步,運用到專案中:

    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <cc:CornerButton ButtonType="OutLine" Width="200" Height="30"
                         cc:Badge.Content="{Binding ElementName=textbox1, Path=Text, UpdateSourceTrigger=PropertyChanged}" Margin="10"/>
        <cc:CornerTextBox x:Name="textbox1" Width="200" Height="30" Text="12"
                          VerticalContentAlignment="Center" WaterText="BadgeContent"/>
    </StackPanel>

cc是表示badge所在的名稱空間,然後你就會發現,你改變textbox的值的時候,badge會跟著textbox的值發生變化哦.

專案github地址:bearhanQ/WPFFramework: Share some experience (github.com)

QQ技術交流群:332035933;

相關文章