Home > database >  How to use properties defined in XAML in the C# code-behind
How to use properties defined in XAML in the C# code-behind

Time:05-28

I have a XAML document with C# code-behind.

In the C# class I define some properties, that I can then set in XAML:

public partial class MyClass : ContentView
{
    public Color MyColor { get; set; }

    public MyClass()
    {
        InitializeComponent()

        //Here I want to use the color
    }
}
<MyClass MyColor="Blue"/>

The problem is that the property is never set. When I try to use it, it still has its default value (White).

Same happens when I use BindableProperties:

public static readonly BindableProperty MyColorProperty = BindableProperty.Create(nameof(MyColor), typeof(Color), typeof(MyClass), Colors.White);

public Color MyColor
{
    get => (Color)GetValue(MyColorProperty);
    set => SetValue(MyColorProperty, value);
}

How are you supposed to do this? I want to use the properties set on this element instance by XAML, but it doesn't work.

CodePudding user response:

It may help to picture c# code instead of xaml. The two are equivalent.

If the use of your component looked like:

var c = new MyClass();
c.MyColor = Color.Blue;

then what is value of MyColor during constructor?

Clearly, it is still White.

To see Blue, use MyColor in any method override. The most common one is OnAppearing:

protected override void OnAppearing()
{
    base.OnAppearing();

    // use MyColor here.
}

CodePudding user response:

The solution was to use OnHandlerChanged. After some experiemnts, I can confirm that XAML properties have been set at this stage, and that it will be called each time.

In code, it would look like this:

protected override void OnHandlerChanged()
{
    base.OnHandlerChanged();
    //Retrieve or use your properties
}

Another proposed solution (if you are using ContentPage) is the method OnAppearing.

  • Related