You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CollectionView中如何绑定ObservableCollection项的RecipeName属性

问题:CollectionView中Label绑定RecipeName属性失效

我有一个CollectionView,希望将Label的Text属性绑定到ObservableCollection集合项的RecipeName属性,但使用Text="{Binding RecipeName}"无法生效,当前只能通过Text="{Binding .}"进行绑定。

View代码

<CollectionView ItemsSource="{Binding Recipes}"
                SelectionMode="None">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="{x:Type x:String}">
            <SwipeView>
                <Grid>
                    <Frame>
                        <Frame.GestureRecognizers>
                            <TapGestureRecognizer 
                                   Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:MainViewModel}}, Path=TapCommand}"
                                   CommandParameter="{Binding .}"/>
                        </Frame.GestureRecognizers>
                        <Label Text="{Binding .}" <!-- Here -->
                               FontSize="24"/>
                    </Frame>
                </Grid>
            </SwipeView>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

ViewModel代码

public MainViewModel()
{
    LoadRecipes();
}

private void LoadRecipes()
{
    Recipes = new ObservableCollection<RecipeModel>
    {
        new RecipeModel
        {
            RecipeName = "Rezept 1", // Here
            Ingredients = "Zutaten 1",
            Steps = "Schritte 1"
        },
        new RecipeModel
        {
            RecipeName = "Rezept 2", // Here
            Ingredients = "Zutaten 2",
            Steps = "Schritte 2"
        }
    };
}

[ObservableProperty]
ObservableCollection<RecipeModel> recipes;

解决方案

已找到有效解决方法,将Label的绑定表达式修改为:

Text="{Binding Source={RelativeSource AncestorType={x:Type model:RecipeModel}}, Path=RecipeName}"

即可实现RecipeName属性的正确绑定。

内容的提问来源于stack exchange,提问作者Florian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:15:32