![](/img/trans.png)
[英].Net MAUI - How to bind to a property in an object that is a List of KeyValuePairs
[英].NET MAUI - How to bind on a property of an ObservableCollection Item
我有一個 CollectionView,我想將標簽的文本綁定到“RecipeName”。
這樣做是行不通的:Text="{Binding RecipeName}"
現在它看起來像:
我的觀點看起來像:
<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 = "Pizza", // Here
Ingredients = "Teig, Belag",
Steps = "Belag auf Teig und danach in den Ofen"
},
new RecipeModel
{
RecipeName = "Burger", // Here
Ingredients = "Brötchen, Fleisch, Belag",
Steps = "Belag und Fleisch auf das Brötchen"
}
};
}
[ObservableProperty]
ObservableCollection<RecipeModel> recipes;
這將綁定整個對象
Text="{Binding .}"
綁定特定屬性
Text="{Binding RecipeName}"
請注意,您只能綁定到公共屬性
您不必設置文本的BindingContext 。 好像有點復雜。 我給出了一些建議,使綁定的使用更適合您的情況。
首先,設置 ContentPage 的BindingContext ,設置MainViewModel 。 你可以在 .xaml 文件中設置它:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
.....
xmlns:viewmodel="clr-namespace:BindBindBind">
<ContentPage.BindingContext>
<viewmodel:MainViewModel/>
</ContentPage.BindingContext>
或者在代碼 behind.cs 文件中:
public MainPage()
{
InitializeComponent();
this.BindingContext = new MainViewModel();
}
然后對於 CollectionView,將 ItemsSource 綁定到MainViewModel中的 Recipes。 默認的BindingContext與其父級相同,即之前設置的MainViewModel 。
<CollectionView ItemsSource="{Binding Recipes}"
SelectionMode="None">
<CollectionView.ItemTemplate>
<DataTemplate>
<SwipeView>
<Grid>
<Frame>
<Frame.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:MainViewModel}}, Path=TapCommand}"
CommandParameter="{Binding .}"/>
</Frame.GestureRecognizers>
<Label Text="{Binding RecipeName}" FontSize="24"/>
</Frame>
</Grid>
</SwipeView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
不需要DataTemplate的 x:DataType。 Recipes是 RecipeModel 實例的集合, DataTemplate定義了每個實例如何顯示。 因此對於每個標簽,Text 屬性應該綁定到每個模型實例的 RecipeName 屬性。
希望對你有效。 如果您還有任何問題,請隨時提問。
有關更多信息,您可以參考使用數據填充 CollectionView和數據綁定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.