我正在嘗試制作一個顯示國家/地區串列的應用程式,當單擊一個國家/地區時,它會顯示該國家/地區的城市串列。
國家.cs:
public class Country {
public string Name { get; set; }
public ImageSource Image { get; set; }
public IList<City> Cities { get; set; }
}
城市.cs:
public class City
{
public string Name { get; set; }
}
在 CountryPageViewModel.cs 中通過以下方式執行導航:
async void OnSelectedCountry(Country country)
{
if (country == null)
{
return;
}
await Shell.Current.GoToAsync($"{nameof(CitiesPage)}?{nameof(CitiesViewModel.Name)}={country.Name}");
}
城市被加載到 CitiesViewModel.cs 中:
[QueryProperty(nameof(Name), nameof(Name))]
public class CitiesViewModel : BaseViewModel
{
private string countryName;
public IList<City> CityList { get; set; }
public string Name
{
get
{
return countryName;
}
set
{
countryName = value;
LoadCities(value);
}
}
public async void LoadCities(string countryName)
{
try
{
Country country = await DataStore.GetItemAsync(cityName);
IList<City> cities = country.Cities;
CityList = cities;
}
catch (Exception)
{
Console.WriteLine("Impossible to load cities");
}
}
}
在 XAML (CitiesPage.xaml) 中:
<CollectionView x:Name="citiesCollectionView" x:DataType="viewmodels:CitiesViewModel"
ItemsSource="{Binding CityList}"
EmptyView="Impossible to load cities" >
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="5" x:DataType="models:City">
<Frame Style="{StaticResource CityCard}">
<Grid RowDefinitions="Auto,Auto"
ColumnDefinitions="Auto" >
<Label Grid.Column="1"
Text="{Binding Name}"
FontAttributes="Bold"
VerticalTextAlignment="Center"
Padding="10"
HeightRequest="50" />
</Grid>
</Frame>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
但是“城市”頁面中沒有顯示任何內容。我已將 CitiesPage.xaml.cs(代碼隱藏)中的 BindingContext 設定為 ViewModel。
我究竟做錯了什么?
uj5u.com熱心網友回復:
對于誰可能有同樣的問題,正如 xamarin 檔案所說
視圖可訪問的所有視圖模型和模型類都應實作 INotifyPropertyChanged 介面。在視圖模型或模型類中實作此介面允許該類在基礎屬性值更改時向視圖中的任何資料系結控制元件提供更改通知。
以下是有關PropertyChanged 的更多提示:
- 如果公共屬性的值發生變化,則始終引發 PropertyChanged 事件。不要假設可以忽略引發 PropertyChanged 事件,因為知道 XAML 系結是如何發生的。
始終為視圖模型或模型中的其他屬性使用其值的任何計算屬性引發 PropertyChanged 事件。
始終在進行屬性更改的方法結束時或在已知物件處于安全狀態時引發 PropertyChanged 事件。引發事件會通過同步呼叫事件的處理程式來中斷操作。如果這發生在操作的中間,當物件處于不安全的、部分更新的狀態時,它可能會將物件暴露給回呼函式。此外,PropertyChanged 事件可能會觸發級聯更改。級聯更改通常需要在級聯更改安全執行之前完成更新。
如果屬性沒有改變,永遠不要引發 PropertyChanged 事件。這意味著您必須在引發 PropertyChanged 事件之前比較舊值和新值。
如果您正在初始化屬性,請不要在視圖模型的建構式期間引發 PropertyChanged 事件。此時視圖中的資料系結控制元件將不會訂閱接收更改通知。
永遠不要在類的公共方法的單個同步呼叫中引發多個具有相同屬性名稱引數的 PropertyChanged 事件。例如,給定一個 NumberOfItems 屬性,它的后備存盤是 _numberOfItems 欄位,如果一個方法在回圈執行程序中將 _numberOfItems 增加了 50 次,那么在所有作業完成后,它應該只在 NumberOfItems 屬性上引發一次屬性更改通知。對于異步方法,為異步延續鏈的每個同步段中的給定屬性名稱引發 PropertyChanged 事件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/381187.html
標籤:C# xaml 沙马林 xamarin.forms 数据绑定
