0

如何将绑定对象转换为字符串?我正在尝试使用可绑定属性将文本绑定到属性,但我收到一条错误消息

无法从 Xamarin.Forms.Binding 转换为 System.string。

我假设 BindableProperty returnType typeof(string) 会抓住这一点。

这是我的前端代码(App.rug.Length 是一个字符串):

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

这是我的后端代码:

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; }
        }
    }

这是错误:

Xamarin.Forms.Xaml.XamlParseException:位置 26:68。无法分配属性“ItemSubText”:“Xamarin.Forms.Binding”和“System.String”之间的类型不匹配

4

1 回答 1

0

您遇到的问题可能是由您用于 subtext 属性的绑定引起的。

您的变量App.rug.Length是静态变量,因此您需要在绑定中指定它,如下所示

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

在哪里

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

还要修复 ItemSubText 属性的属性访问器

public string ItemSubText
{
    get { return (string)GetValue (SubTextProperty); }
    set { SetValue (SubTextProperty, value); }
}
于 2017-01-09T03:49:40.700 回答