我在如何显示绑定(bind)上下文方面遇到问题,我将其放在后面的代码中,但它不起作用。它说找不到数据上下文
我尝试了其他方法,但它仍然无法读取我的绑定(bind)。这是我的 xaml 代码
<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; }
}
}
没有错误。它会运行,但它不会读取我的绑定(bind),即使我已经在我的代码隐藏中调用它。
最佳答案
这是一个简单的绑定(bind)问题。如果要在xaml中使用绑定(bind),则需要使用MVVM设置一个实现INotifyChanged接口(interface)的ViewModel作为绑定(bind)上下文。您可以查看official document关于它。
此外,您还可以给ListView起一个名称,例如:
<ListView x:Name = "listview">
并在页面中设置ItemSource如:
listview.ItemSource = Recipes;
ListView可以查看官方文档.
关于c# - 未找到用于绑定(bind)配方的数据上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73665304/