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
相关产品推荐
相关产品推荐

