我有一个问题,如何显示我的绑定上下文,我有它在我的代码背后,但它不工作。它说没有数据上下文找到
我尝试了其他方法,但它仍然不能读取我的绑定。
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App1.RecipePage1"
Title="Recipe Name">
<ContentPage Title="Ingredients">
<StackLayout>
<ListView ItemsSource="{Binding Recipes}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Frame>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Text="{Binding Ingredient}"></Label>
<Label Grid.Row="0" Grid.Column="1" Text="{Binding Quantity}"></Label>
</Grid>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
这是我的代码
public partial class RecipePage1 : TabbedPage
{
public IList<Recipe> Recipes { get; set; }
public RecipePage1()
{
InitializeComponent();
Recipes = new List<Recipe>();
Recipes.Add(new Recipe() { Ingredient = "Kimchi", Quantity = "100 Grams" });
Recipes.Add(new Recipe() { Ingredient = "Noodle", Quantity = "80 Grams" });
Recipes.Add(new Recipe() { Ingredient = "Scallions", Quantity = "150 Grams" });
Recipes.Add(new Recipe() { Ingredient = "Spinach", Quantity = "200 Grams" });
Recipes.Add(new Recipe() { Ingredient = "Prawns", Quantity = "500 Grams" });
BindingContext = this;
}
public class Recipe
{
public string Ingredient { get; set; }
public string Quantity { get; set; }
}
}
1条答案
按热度按时间nwnhqdif1#
这是一个简单的绑定问题,如果想在xaml中使用绑定,需要使用MVVM设置一个实现INotifyChanged接口的ViewModel作为绑定上下文,可以查看official document。
此外,您也可以为ListView命名,例如:
并在页面中设置ItemSource如:
您可以查看有关ListView的官方文件。