<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:TestApp.ViewModels"
x:Class="TestApp.Views.MasterPage"
Title="This is the title">
<StackLayout>
<ListView x:Name="listView">
<ListView.ItemsSource>
<x:Array Type="{x:Type viewModels:MasterPageItem}">
<viewModels:MasterPageItem Title="{Binding Item1}"/>
<viewModels:MasterPageItem Title="{Binding Item2}"/>
</x:Array>
</ListView.ItemsSource>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Label Text="{Binding Title}" VerticalTextAlignment="End"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
所以我收到了构建错误:&#34;没有为标题&#39;找到属性,可绑定属性或事件,或者在值和属性之间存在不匹配类型。&#34;我试图将MasterPageItem Title属性绑定到我视图中的值(这样做是为了让我可以在运行时通过选择所需语言来翻译值)。 Item1和Item2是MasterPage视图中的属性,而Title则存在于MasterPageItem中。 ListView中的Label绑定到MasterPageItem Title属性。
我不确定我在这里做错了什么,所以任何帮助都会受到赞赏。
答案 0 :(得分:1)
如果此MasterPageItem
引用了在项目中添加MasterDetailPage
时通常为处理菜单选择而创建的类,那么它确实没有BindableProperty
。
这是我们使用的默认模型:
public class MainPageMenuItem
{
public MainPageMenuItem()
{
TargetType = typeof(MainPageDetail);
}
public int Id { get; set; }
public string Title { get; set; }
public Type TargetType { get; set; }
}
如果你想使用绑定,你必须使这个类成为BindableObject
,然后将其属性更改为可绑定的类。
像这样:
public class MainPageMenuItem : BindableObject
{
public MainPageMenuItem()
{
TargetType = typeof(MainPageDetail);
}
public readonly static BindableProperty IdProperty = BindableProperty.Create(nameof(Id), typeof(int), typeof(MainPageMenuItem));
public int Id
{
get { return (int)GetValue(IdProperty); }
set { SetValue(IdProperty, value); }
}
public readonly static BindableProperty TitleProperty = BindableProperty.Create(nameof(Title), typeof(string), typeof(MainPageMenuItem));
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public readonly static BindableProperty TargetTypeProperty = BindableProperty.Create(nameof(TargetType), typeof(Type), typeof(MainPageMenuItem));
public Type TargetType
{
get { return (Type)GetValue(TargetTypeProperty); }
set { SetValue(TargetTypeProperty, value); }
}
}
我希望它有所帮助。