Home > Mobile >  How do I bind a value to a referenced custom content page (XAML)
How do I bind a value to a referenced custom content page (XAML)

Time:09-30

I created a custom ContentPage to show a circle avatar with initials. When I pass a value via binding it comes up as null, I debugged to check this. Can someone help me please? Thanks.

HomePage.xaml

<views:CircleView CircleText="{Binding Initials}"/>

CircleView.xaml

<Frame x:Name="circleFrame">
    <Label  x:Name="circleLabel"
            Text="{Binding CircleText}"/>
</Frame>

CircleView.xaml.cs

public partial class CircleView : ContentView
{
    public CircleView()
    {
        InitializeComponent();
        BindingContext = this;
    }

    public static readonly BindableProperty CircleTextProperty =
BindableProperty.Create(nameof(CircleText), typeof(string), typeof(CircleView), null);

    public string CircleText
    {
        get { return (string)GetValue(CircleTextProperty); }
        set { SetValue(CircleTextProperty, value); }
    }
}

CodePudding user response:

In CircleView.xaml, you should include a source to the binding, would be something like:

<ContentView x:Name="Self">
<Frame x:Name="circleFrame">
    <Label  x:Name="circleLabel"
            Text="{Binding source={x:reference Self}, Path=CircleText}"/>
</Frame>
</ContentView>

CodePudding user response:

You could try the code below.

CircleView.xaml:

   <Frame x:Name="circleFrame">
        <Label  x:Name="circleLabel"/>
    </Frame>

CircleView.xaml.cs:

    public CircleView()
    {
        InitializeComponent();

    }

    public static readonly BindableProperty CircleTextProperty =
    BindableProperty.Create(nameof(CircleText), typeof(string), typeof(CircleView), propertyChanged:(b,o,n)=>(b as CircleView).OnChanged());

    private void OnChanged()
    {
        circleLabel.Text = CircleText;
    }

    public string CircleText
    {
        get { return (string)GetValue(CircleTextProperty); }
        set { SetValue(CircleTextProperty, value); }
    }

MainPage.xaml:

     <views:CircleView CircleText="{Binding Initials}"/>

MainPage.xaml.cs:

    public string Initials { get; set; }
    public MainPage()
    {
        InitializeComponent();
        Initials = "Hello";
        this.BindingContext = this;
    }
  • Related