如何将控件的默认字体大小作为静态变量?

时间:2018-02-21 12:16:22

标签: c# uwp

我想将GeometryCollection中的图片缩放到Button控件的默认字体大小,除此之外,我想基于默认字体静态地执行此操作,而不是动态地在函数中执行此操作。任何想法如何做到这一点?

以下是我的代码示例:

// UWP C# Code
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Shapes;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Data;

namespace GridNineExperiment
{    
    public class Hamburger : Button
    {    
        //static Size txsize = /* Default Font Size of Button, ie. Height and Width of Font Character*/

        // Change using txsize to calculate X,Y,Height,Width
        static GeometryCollection DataHamburger = new GeometryCollection
        {
            new RectangleGeometry {Rect = new Rect{X = 0, Y = 0, Width = 20, Height = 5 }},
            new RectangleGeometry {Rect = new Rect{X = 0, Y = 10, Width = 20, Height = 5 }},
            new RectangleGeometry {Rect = new Rect{X = 0, Y = 20, Width = 20, Height = 5 }},
        };

        static Path PathHamburger = new Path
        {
            Fill = new SolidColorBrush(Colors.White),
            Stroke = new SolidColorBrush(Colors.Black),
            StrokeThickness = 1.0,
            Data = new GeometryGroup { Children = DataHamburger } 
        };

    public Hamburger()
    {
        Content = PathHamburger;
    }
}

1 个答案:

答案 0 :(得分:0)

我发现你不应该将按钮内容属性设置为静态,因为你只能创建一个Button实例。但是,这是对我有用的解决方案:

using Windows.Foundation;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Shapes;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Data;

namespace GridNineExperiment
{
    public class HamburgerButton : Button
    {
        public HamburgerButton()
        {
            // Default Font Height of Button
            double H = (double)Button.FontSizeProperty.GetMetadata(typeof(double)).DefaultValue;

            double A = H / 5;

            GeometryCollection DataHamburger = new GeometryCollection
        {
            new RectangleGeometry {Rect = new Rect{X = 0, Y = 0*A,  Width = 20, Height = A/2 }},
            new RectangleGeometry {Rect = new Rect{X = 0, Y = 2*A,  Width = 20, Height = A/2 }},
            new RectangleGeometry {Rect = new Rect{X = 0, Y = 4*A,  Width = 20, Height = A/2 }},
        };

            Path PathHamburger = new Path
            {
                Fill = new SolidColorBrush(Colors.Black),
                Stroke = new SolidColorBrush(Colors.Black),
                StrokeThickness = 1.0,
                Data = new GeometryGroup { Children = DataHamburger }
            };

            Content = PathHamburger;
        }
    }