Convert Xamarin.Forms.Binding into System.string

1.6k Views Asked by At

How would you convert a binding object into a string? I'm trying to bind text to a property using a bindable property, but I'm getting an error that says

cannot convert from Xamarin.Forms.Binding to System.string.

I assumed the BindableProperty returnType typeof(string) would have caught this.

Here's my front-end code (App.rug.Length is a string):

    <local:MenuItem ItemTitle="Length" ItemImage="icons/blue/next" ItemSubText="{Binding App.rug.Length}" PageToo="{Binding lengthpage}"/>

Here's my back-end code:

public class MenuItem : ContentView

    {
        private string itemsubtext { get; set; } 


        public static BindableProperty SubTextProperty = BindableProperty.Create("ItemSubText", typeof(string), typeof(MenuItem), null, BindingMode.TwoWay);

        public MenuItem()
        {
            var menuTapped = new TapGestureRecognizer();
            menuTapped.Tapped += PushPage;


            StackLayout Main = new StackLayout
            {
                Children = {

                    new SectionLine(),
                    new StackLayout {

                        Padding = new Thickness(10),
                        Orientation = StackOrientation.Horizontal,
                        HorizontalOptions = LayoutOptions.Fill,
                        Children = {

                            new Label {

                                Margin = new Thickness(10, 2, 10, 0),
                                FontSize = 14,
                                TextColor = Color.FromHex("#c1c1c1"),
                                HorizontalOptions = LayoutOptions.End,
                                Text = this.ItemSubText

                            }
                        }
                    }
                }
            };

            Main.GestureRecognizers.Add(menuTapped);
            Content = Main;
        }

        public string ItemSubText
        {
            get { return itemsubtext; }
            set { itemsubtext = value; }
        }
    }

Here is the error:

Xamarin.Forms.Xaml.XamlParseException: Position 26:68. Cannot assign property "ItemSubText": type mismatch between "Xamarin.Forms.Binding" and "System.String"

1

There are 1 best solutions below

0
On

the issue you are getting is probably caused by the binding you have used for the subtext property.

Your variable App.rug.Length is a static variable so therefore you will need to specify it in the binding like below

<local:MenuItem ItemTitle="Length" ItemImage="icons/blue/next" ItemSubText="{Binding Source={x:Static local:App.rug.Length}}" PageToo="{Binding lengthpage}"/>

where

xmlns:local="clr-namespace:{App Namespace here}"

Also fix up your property Accessors for ItemSubText property

public string ItemSubText
{
    get { return (string)GetValue (SubTextProperty); }
    set { SetValue (SubTextProperty, value); }
}