无法将参数传递给ContentView

时间:2017-11-15 12:49:40

标签: c# xamarin xamarin.forms

我有下一个ContentView代码:

     <StackLayout>
        <StackLayout Orientation="Horizontal">
          <Frame
            HeightRequest="{Binding Height}"
            WidthRequest="{Binding Width}"
            CornerRadius="{Binding Radius}"
            Margin="0"
            Padding="0">
            <Label Text="Some text" />
          </Frame>
        </StackLayout>
    </StackLayout>

    public partial class CicrleView : ContentView
    {
        public int XCoord { get; set; }
        public int YCoord { get; set; }
        public int Radius { get; set; }

        private int width;
        public int Width
        {
            get
            {
                return Radius * 2;
            }
            set
            {
                this.width = value;
            }
        }

        private int height;
        public int Height
        {
            get
            {
                return Radius * 2;
            }
            set
            {
                this.height = value;
            }
        }

        public CicrleView()
        {
            InitializeComponent();            
        }        
    }

当我使用CircleView并传递参数“Radius”<local:CicrleView Radius="50" />时,不会发生任何事情(属性Radius不会初始化)。如何解决此问题并在CircleView中初始化Radius属性?

1 个答案:

答案 0 :(得分:1)

Radius的值是在实例化CircleView之后设置的 - 因为没有属性更改通知 - 它不会传播到内部Frame.CornerRadius

要解决此问题,请为Radius创建一个可绑定属性,或者确保调用PropertyChanged

public int Radius
{
    get { return _radius; }
    set { _radius = value; OnPropertyChanged(nameof(Radius)); }
}

此外,请确保将父主机视图设置为绑定源。

CornerRadius="{Binding Radius, Source=_parentHost}

并将x:Name属性分配给CircleView XAML中的根标记:

<ContentView .... x:Name="_parentHost" ..