【问题标题】:Xamarin.Forms set size of custom viewXamarin.Forms 设置自定义视图的大小
【发布时间】:2017-01-24 08:30:21
【问题描述】:

如何在 xaml 中设置自定义视图或更具体地说是自定义 BoxView 的大小?目前,视图占据了整个设备大小,而不是请求的 20x20。

这是我的 xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Beltpack"
             xmlns:controls="clr-namespace:Beltpack.Views;assembly=Beltpack"
             x:Class="Beltpack.MainPage">

  <controls:bpButton Height="20" Width="20" HeightRequest="20" WidthRequest="20" />

</ContentPage>

我的按钮源自 BoxView(目前不做任何事情)

using Xamarin.Forms;

namespace Beltpack.Views {
    public class bpButton : BoxView {

        public bpButton() { }

    }

}

还有我的自定义渲染器

using Android.Graphics;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms;
using Beltpack.Views;
using Beltpack.Droid;

[assembly: ExportRenderer(typeof(bpButton), typeof(bpButtonRenderer))]

namespace Beltpack.Droid {
    public class bpButtonRenderer : BoxRenderer {

        public bpButtonRenderer() {}

        protected override void OnDraw(Canvas canvas) {
            bpButton btn = (bpButton)this.Element;

            Paint paint = new Paint();
            paint.Color = Android.Graphics.Color.Aqua;

            canvas.DrawCircle((int)(btn.WidthRequest * .5), (int)(btn.HeightRequest * .5), (int)(btn.WidthRequest * .5), paint);
        }        
    }
}

【问题讨论】:

  • 您是否检查过 WidthRequest 和 HeightRequest 在 OnDraw 函数中的值是否正确?我怀疑您必须强制重绘 OnElementChanged 函数。

标签: c# xamarin xamarin.forms


【解决方案1】:

除了设置WidthRequestHeightRequest,您还必须设置HorizontalOptionsVerticalOptions 设置。

为什么?我不知道,但这是其他地方建议的解决方案,并且一直对我有用。

看起来你想要它在中心,所以你可以简单地写

<controls:bpButton 
    Height="20"
    Width="20" 
    HeightRequest="20"
    WidthRequest="20"
    HorizontalOptions="Center"
    VerticalOptions="Center" />

【讨论】:

  • 谢谢!由于某种原因,它有点偏离中心......但我希望能够弄清楚......
猜你喜欢
  • 2016-05-29
  • 1970-01-01
  • 2020-04-25
  • 1970-01-01
  • 2012-09-05
  • 2012-03-03
  • 2015-12-12
  • 1970-01-01
相关资源
最近更新 更多