[英]In Xamarin.Forms, how to Bind to list of custom class, for ListView and print custom class properties?
在.xaml 文件中,我試圖將一個列出的自定義類作為 ObeservableCollection 對象進行綁定。 我可以成功更新我的變量並更新 ObservableCollection。 我可以將其渲染為:
<ListView ItemSource="{Binding myCustomObservableCollection}"/>
但是,即使我可以確定列表中的條目數,我也無法訪問自定義類的屬性。 我試過這個,但沒有成功,因為列表的行是空的。 即使使用Text="{Binding Id}"
也不起作用,因為它告訴我“Id”不是 myCustomViewModel 中的屬性:
<ListView
x:DataType="vm:CustomtViewModel"
BackgroundColor="LightSlateGray"
HasUnevenRows="True"
HorizontalOptions="FillAndExpand"
ItemsSource="{Binding myCustomObservableCollection}"
SeparatorColor="Black">
<ListView.ItemTemplate>
<DataTemplate>
<label Text="{Binding Source={StaticSource myCustomClass}", Path=Id}/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
當然,我已將我的自定義類插入到 the.xaml 中:
<ContentPage.Resources>
<local:myCustomClass x:Key="myCustomClass" />
</ContentPage.Resources>
Id 是我模型中公共類所需的屬性之一
namespace myApp.Models {
public class myCustomClass : INotifyPropertyChanged
{
private string _id;
public event PropertyChangedEventHandler PropertyChanged;
public string Id
{
get => _id;
set {
_id = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Id)));
}
}
}
}
所以我想知道如何有效地讀取列表的每個條目作為一個對象,我可以解析其中的屬性。
非常感謝
您是否查看過有關ListView 中的 Binding Cells的官方文檔? myCustomClass 不必從 INotifyPropertyChanged 接口繼承。
只要確保有public ObservableCollection<myCustomClass> { get; set; }
public ObservableCollection<myCustomClass> { get; set; }
public ObservableCollection<myCustomClass> { get; set; }
你的視圖模型中。 如:
public class CustomtViewModel
{
public ObservableCollection<myCustomClass> myCustomObservableCollection { get; set; }
public CustomtViewModel()
{
// you can initialize the myCustomObservableCollection's data in the construction method.
}
}
此外,我看到您將x:DataType="vm:CustomtViewModel"
用於列表視圖。 官方文件說:
將 VisualElement 上的 x:DataType 屬性設置為 VisualElement 及其子項將綁定到的對象的類型。
所以你可以像 Jason 說的那樣綁定 Id:
<ListView.ItemTemplate>
<DataTemplate>
<Label Text={Binding Id}/>
</DataTemplate>
</ListView.ItemTemplate>
另外可以參考github上關於listview mvvm綁定的官方示例,這是viewmodel的代碼和page的代碼。
還要感謝 Liyun Zhang 和 ToolmakerSteve 我想出了一個解決方案。 確實設置正確的 x:DataType 很重要,我發現它甚至可以多次指向不同的類,鏈接不同類型的數據這是我現在在 xaml 中的 ListView:
<ListView
x:Name="customListName"
x:DataType="vm:CustomViewModel"
ItemsSource="{Binding myCustomObservableCollection}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:myCustomClass"> <!--THIS SAVED THE DAY-->
<ViewCell>
<Label Text="{Binding Id}" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
現在從列表中提取的對象被正確地讀取引用到它自己的類。
訣竅是在我像這樣在 xaml 中添加引用后將x:DataType="local:myCustomClass"
添加到 DataTemplate 標記:
<ContentPage.Resources>
<local:myCustomClass x:Key="myCustomClass" />
</ContentPage.Resources>
(如果其他人遇到同樣的問題,我也在這里插入以便於閱讀)
它就像一個魅力!
希望這可以使其他人免於頭痛。 干杯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.