将对象绑定到xamarin表单中的自定义控件
问题描述:
我试图通过填充可重用控件的页面来构建我的应用程序。我想在运行时将对象绑定到自定义控件,以便根据页面上的属性填充它们的属性。到目前为止,我尝试过的不正常,我想知道是否有更好的方法。我得到的当前错误说,它不能将绑定类型转换为字符串。这是我到目前为止尝试过的一个例子。将对象绑定到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"
};
}
}
答
这里需要使用绑定的属性是如何用一个例子他们:
public static readonly BindableProperty ImageProperty =
BindableProperty.Create(nameof(Image), typeof(ImageSource), typeof(DashEntry), null);
public ImageSource Image
{
get
{
return (ImageSource)GetValue(ImageProperty);
}
set
{
SetValue(ImageProperty, value);
}
}
而关于它的文档:
https://developer.xamarin.com/guides/xamarin-forms/xaml/bindable-properties/
那是什么我一直在尝试使用,但它不断给我一个错误说,它不能转换类型结合System.String类型。当我使用如下绑定设置属性时,它会越来越绊倒: