0
我試圖通過填充可重用控件的頁面來構建我的應用程序。我想在運行時將對象綁定到自定義控件,以便根據頁面上的屬性填充它們的屬性。到目前爲止,我嘗試過的不正常,我想知道是否有更好的方法。我得到的當前錯誤說,它不能將綁定類型轉換爲字符串。這是我到目前爲止嘗試過的一個例子。將對象綁定到xamarin表單中的自定義控件
視圖模型:
public class MenuItem
{
public Page pageTo { get; set; }
public string title { get; set; }
public string subtitle { get; set; }
public string iconPath { get; set; }
}
public class VMMenuItem : ContentView
{
public MenuItem item { get; set; }
public static BindableProperty ItemProperty = BindableProperty.Create("Item", typeof(MenuItem), typeof(VMMenuItem), null, BindingMode.TwoWay,);
public VMMenuItem()
{
var menuTapped = new TapGestureRecognizer();
StackLayout Main = new StackLayout
{
BindingContext = item,
Children = {
new SectionLine(),
new StackLayout
{
Padding = new Thickness(10),
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.Fill,
Children = {
new Label {
Margin = new Thickness(10, 2, 0, 0),
HorizontalOptions = LayoutOptions.StartAndExpand,
Text = "{Binding title}"
},
new Label
{
Margin = new Thickness(10, 2, 10, 0),
FontSize = 14,
TextColor = Color.FromHex("#c1c1c1"),
HorizontalOptions = LayoutOptions.End,
Text = "{Binding subtitle}"
},
new Image {
HorizontalOptions = LayoutOptions.End,
Source = "{Binding iconPath}",
WidthRequest = 20
}
}
}
}
};
Main.GestureRecognizers.Add(menuTapped);
Content = Main;
}
public MenuItem menuItem
{
get { return (MenuItem)GetValue(ItemProperty); }
set { SetValue(ItemProperty, value); }
}
}
頁前端:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:local="clr-namespace:TamarianApp;assembly=TamarianApp" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="TamarianApp.RugPage">
<Grid>
<local:VMMenuItem menuItem="{Binding lengthMenuItem}"></local:VMMenuItem>
</Grid>
</ContentPage>
頁後端:
public partial class RugPage : ContentPage
{
MenuItem lengthMenuItem;
public RugPage()
{
InitializeComponent();
App.currentPage = this;
BindingContext = App.rug;
lengthMenuItem = new MenuItem
{
title = "length",
iconPath = "icons/blue/next",
subtitle = "somelength"
};
}
}
那是什麼我一直在嘗試使用,但它不斷給我一個錯誤說,它不能轉換類型結合System.String類型。當我使用如下綁定設置屬性時,它會越來越絆倒: