【问题标题】:Convert Xamarin.Forms.Binding into System.string将 Xamarin.Forms.Binding 转换为 System.string
【发布时间】:2017-01-06 21:01:39
【问题描述】:

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

无法从 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”

【问题讨论】:

    标签: xamarin.forms xamarin-binding


    【解决方案1】:

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

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

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

    在哪里

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

    同时修复 ItemSubText 属性的属性访问器

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

    【讨论】:

      猜你喜欢
      • 2019-12-07
      • 2012-09-07
      • 2010-10-23
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      • 2017-04-09
      • 2010-10-14
      • 1970-01-01
      相关资源
      最近更新 更多