将 Xamarin.Forms.Binding 转换为 System.string



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

无法从 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"之间的类型不匹配 和"系统字符串"

您遇到的问题可能是由您用于 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); }
}

相关内容

最新更新