Avalonia 使用元件(UserControl) 子類別從父類別 繼承的只有非事件(event)相關,所有事件都要重新撰寫

Avalonia 使用元件(UserControl) 子類別從父類別 繼承的只有非事件(event)相關,所有事件都要重新撰寫

Avalonia 使用元件(UserControl) 子類別從父類別 繼承的只有非事件(event)相關,所有事件都要重新撰寫


資料來源: 自己


父類別XMAL

<UserControl xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
			 x:Name="root"
             x:Class="VPOS_Avalonia.BaseButton" MinWidth="30" MinHeight="30">
	<!-- Grid 疊加圖層準備 -->
	<Grid RowDefinitions="*" ColumnDefinitions="*">
		<!-- Border 圓弧邊框-->
		<Border Name="Bd_Base" Grid.Row="0" CornerRadius="5" 
				BorderBrush="{Binding BorderColor, ElementName=root}"  BorderThickness="1" 
				Background="{Binding BackgroundColor, ElementName=root}" >
			
			<Grid RowDefinitions="*" ColumnDefinitions="*">
				
				<TextBlock Name="TB_Base" TextWrapping="WrapWithOverflow" HorizontalAlignment="Center" VerticalAlignment="Center"
				  FontSize="{Binding TextSize, ElementName=root}" 
				  Text="{Binding Text, ElementName=root}"
				  Background="{Binding BackgroundColor, ElementName=root}" 
				  Foreground="{Binding TextColor, ElementName=root}"/>
				
				<Canvas>
					<!-- Drawing area
					<Rectangle Fill="Blue" Width="10" Height="10" Stroke="Red" StrokeThickness="2"/>
					 -->			
				</Canvas>			
			</Grid>
			
		</Border>
	</Grid>
	
</UserControl>


父類別CODE

using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using System;
using static System.Net.Mime.MediaTypeNames;

namespace VPOS_Avalonia;

public partial class BaseButton : UserControl
{
    // 可以在此添加額外的屬性、事件或方法
    public static readonly StyledProperty<double> TextSizeProperty =
        AvaloniaProperty.Register<BaseButton, double>(nameof(TextSize));
    public static readonly StyledProperty<string> TextProperty =
        AvaloniaProperty.Register<BaseButton, string>(nameof(Text));
    public static readonly StyledProperty<IBrush> TextColorProperty =
        AvaloniaProperty.Register<BaseButton, IBrush>(nameof(TextColor));
    public static readonly StyledProperty<IBrush> BackgroundColorProperty =
        AvaloniaProperty.Register<BaseButton, IBrush>(nameof(BackgroundColor));
    public static readonly StyledProperty<IBrush> BorderColorProperty =
    AvaloniaProperty.Register<BaseButton, IBrush>(nameof(BorderColor));

    public double TextSize
    {
        get => GetValue(TextSizeProperty);
        set => SetValue(TextSizeProperty, value);
    }
    public string Text
    {
        get => GetValue(TextProperty);
        set => SetValue(TextProperty, value);
    }
    public IBrush BackgroundColor
    {
        get => GetValue(BackgroundColorProperty);
        set => SetValue(BackgroundColorProperty, value);
    }
    public IBrush TextColor
    {
        get => GetValue(TextColorProperty);
        set => SetValue(TextColorProperty, value);
    }
    public IBrush BorderColor
    {
        get => GetValue(BorderColorProperty);
        set => SetValue(BorderColorProperty, value);
    }

    // Declare the external click event
    public event EventHandler<RoutedEventArgs> ExternalClicked;

    public BaseButton()
    {
        InitializeComponent();

        // Attach the event handler for TextBlock's PointerPressed event
        Bd_Base.PointerPressed += OnClicked;
        
    }
    // Event handler method
    private void OnClicked(object sender, PointerPressedEventArgs e)
    {
        // Raise the external click event
        ExternalClicked?.Invoke(this, e);
    }
}


子類別CODE

using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using VPOS;

namespace VPOS_Avalonia
{
    public class CustBtn : BaseButton
    {
        public int m_intSID;
        private bool m_blnAutoFontSize;
        public IBrush m_BackgroundColor00;
        public IBrush m_BackgroundColor01;

        public decimal m_intPrice;
        public String m_StrProductCode;
        public bool m_blnspec;
        public List<product_Var> m_product;
        public List<int> m_same_group_sid;
        public int m_min_count;
        public int m_max_count;

        public String m_Strproduct_type;//類型
        public int m_inttax_sid; //稅率編號 ; 產品若沒有稅率資料[m_tax_sid=0],就直接從company和tax_data取出預設值
        public int m_inttax_rate; //稅率
        public String m_Strtax_type;//稅率類型
        public int m_inttax_fee; //稅率金額

        public void InitData(int intSID)
        {
            m_intSID = intSID;
        }

        public void InitDisplay(IBrush BorderColor, IBrush BackgroundColor00, IBrush BackgroundColor01, String Text, double FontSize, bool blnAutoFontSize = false, int intMinimumWidth = 0, int intMinimumHeight = 0)
        {
            this.MinWidth = (intMinimumWidth > 0) ? intMinimumWidth : this.MinWidth;
            this.MinHeight = (intMinimumHeight > 0) ? intMinimumHeight : this.MinHeight;

            this.BorderColor = BorderColor;
            this.BackgroundColor = (IsEnabled) ? BackgroundColor00 : Brush.Parse("#FFCCCCCC");
            m_BackgroundColor00 = BackgroundColor00;
            m_BackgroundColor01 = BackgroundColor01;

            this.TextColor = (IsEnabled) ? Brushes.White : Brush.Parse("#FFA0A0A0");
            if (FontSize > 0)
            {
                this.TextSize = FontSize;
                m_dblFontSize = FontSize;
            }

            this.Text = Text;
            m_blnAutoFontSize = blnAutoFontSize;

        }

        public void SetText(String Text)
        {
            this.Text = Text;
            if (Text.Length > 0)
            {
                m_blnChange = false;
                this.TextSize = m_dblFontSize;
                FontSizeChanged();
            }
        }

        public String GetText()
        {
            this.IsVisible = true;
            return this.Text;
        }

        public void SetBackgroundColor(IBrush BackgroundColor)
        {
            this.BackgroundColor = BackgroundColor;
        }

        public void SetBackgroundColor(bool blnClick = false)
        {
            if (blnClick)
            {
                this.BackgroundColor = (IsEnabled) ? m_BackgroundColor01 : Brush.Parse("#FFCCCCCC");
                this.TextColor = (IsEnabled) ? Brushes.White : Brush.Parse("#FFA0A0A0");
            }
            else
            {
                this.BackgroundColor = (IsEnabled) ? m_BackgroundColor00 : Brush.Parse("#FFCCCCCC");
                this.TextColor = (IsEnabled) ? Brushes.White : Brush.Parse("#FFA0A0A0");
            }
        }

        // Declare the external click event
        public event EventHandler<RoutedEventArgs> ExternalClicked;

        public CustBtn()
        {
            InitializeComponent();
            m_intSID = 0;
            m_blnAutoFontSize = false;
            this.MinWidth = 40;
            this.MinHeight = 45;
            m_dblContentWidth = 0.0f;
            m_dblContentHeight = 0.0f;
            m_dblFontSize = 0.0f;
            m_blnChange = false;
            this.LayoutUpdated += OnLayoutUpdated;
            // Attach the event handler for TextBlock's PointerPressed event
            Bd_Base.PointerPressed += OnClicked;
        }

        private void OnClicked(object sender, PointerPressedEventArgs e)
        {
            // Raise the external click event
            ExternalClicked?.Invoke(this, e);
        }

        private double m_dblBoundsWidth;
        private double m_dblBoundsHeight;
        private void OnLayoutUpdated(object sender, EventArgs e)
        {
            m_dblBoundsWidth = this.Bounds.Width;
            m_dblBoundsHeight = this.Bounds.Height;
            if(m_blnAutoFontSize)
            {
                SetText(Text);
            }

        }
        private double m_dblFontSize;
        private double m_dblContentWidth;
        private double m_dblContentHeight;
        private bool m_blnChange = false;

        private void FontSizeChanged()
        {
            /*
             透過 按鈕大小變化事件 配合計算文字長度 進而縮小字型大小 使其文字不要被裁切
            */
            double w = 0.38;//字型1 -> 寬度
            double h = 0.96;//字型1 -> 高度

            //int intCount = 0;

            string strData = RemoveNewLines(this.Text).Replace("...", "");
            int intLen = GetCustomLength(strData);

            m_dblContentWidth = m_dblBoundsWidth - 4;//無條件捨取(2 -> Padding 1)
            m_dblContentHeight = m_dblBoundsHeight - 4;//無條件捨取(2 -> Padding 1)

            if (!m_blnChange)
            {
                m_blnChange = true;
                double dblNewLineCount = 0;
                do
                {
                    dblNewLineCount = Math.Ceiling((this.TextSize * intLen * 1.25 * w) / m_dblContentWidth);

                    if ((dblNewLineCount * h * this.TextSize * 1.25) <= m_dblContentHeight)
                    {
                        break;
                    }
                    else
                    {
                        //intCount++;
                        this.TextSize = this.TextSize - 0.3;
                    }

                }
                while (true);

                /*
                //自動放大字體
                if(intCount == 0)
                {
                    double dblOriginalCount = dblNewLineCount;
                    do
                    {
                        dblNewLineCount = Math.Ceiling((Content.FontSize * intLen * 1 * w) / m_dblContentWidth);

                        if ( (dblNewLineCount == dblOriginalCount) && ((dblNewLineCount * h * Content.FontSize * 1) < m_dblContentHeight) )
                        {
                            intCount++;
                            Content.FontSize = Content.FontSize + 0.5;
                        }
                        else
                        {
                            break;
                        }

                    }
                    while (true);
                }
                //*/
            }
        }

        public string RemoveNewLines(string input, string strReplace = "")//自動剔除字串中的所有換行符號
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }

            // 使用正則表達式移除換行符號
            return Regex.Replace(input, @"\r\n|\r|\n", strReplace);
        }

        private int GetCustomLength(string text)//計算字串長度 中文=3
        {
            int length = 0;
            foreach (char c in text)
            {
                // 判斷字符是否為中文
                if (c >= 0x4E00 && c <= 0x9FFF)
                {
                    length += 3; // 中文字符算作3個英文字
                }
                else
                {
                    length += 1; // 其他字符算作一個英文字
                }
            }
            return length;
        }
    }
}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *