XAML 未找到绑定处方的数据上下文

mfpqipee  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(172)

我有一个问题,如何显示我的绑定上下文,我有它在我的代码背后,但它不工作。它说没有数据上下文找到
我尝试了其他方法,但它仍然不能读取我的绑定。

<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; }
        }
    }

there is no error, it will run but it doesnt read my binding even if i already called it on my behind

nwnhqdif

nwnhqdif1#

这是一个简单的绑定问题,如果想在xaml中使用绑定,需要使用MVVM设置一个实现INotifyChanged接口的ViewModel作为绑定上下文,可以查看official document
此外,您也可以为ListView命名,例如:

<ListView x:Name = "listview">

并在页面中设置ItemSource如:

listview.ItemSource = Recipes;

您可以查看有关ListView的官方文件。

相关问题