2017-01-23 84 views
1

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

enter image description here

这里是我的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); 
     }   
    } 
} 
+0

你检查,如果WidthRequest和HeightRequest有正确的价值观,在OnDraw函数?我怀疑你必须强制重写OnElementChanged函数。 – Gusman

回答

1

除了设置WidthRequestHeightRequest,还必须设置你的HorizontalOptionsVerticalOptions设置。

为什么?我不知道,但这是其他地方提出的解决方案,并一直为我工作。

它看起来像你希望它在中央,所以你可以简单的写

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

谢谢!出于某种原因,它有点偏离中心......但我希望能够弄清楚...... – bwoogie

相关问题