我ListView在 ViewModel 的串列中將標簽系結到專案的屬性時遇到了一些問題。
ListView 的 ItemsSource 可以很好地系結到串列,但我無法訪問該串列中專案的屬性。誰能看到我錯過了什么?
編譯器訊息:
XFC0045 Binding: Property "Name" not found on "SocketApp.Pages.ConnectionPageViewModel".
XAML:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="SocketApp.Pages.ConnectionsPage"
xmlns:local="clr-namespace:SocketApp.Pages"
x:DataType="local:ConnectionPageViewModel"> <!-- ViewModel Set -->
<StackLayout >
<!-- Binding the List to the ListView -->
<!-- This works fine -->
<ListView ItemsSource="{Binding ListItems}" HasUnevenRows="True" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell >
<Grid Padding="5" HeightRequest="50">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="9*" />
</Grid.ColumnDefinitions>
<StackLayout Orientation="Vertical" Grid.Column="1" Margin="5" >
<!-- Try to Bind to a property of an item within the list -->
<!-- This is what is not working -->
<Label Grid.Column="1" Text="{Binding Name}" FontAttributes="Bold" />
<Label Grid.Row="1" Grid.Column="1" Text="{Binding Address}" FontAttributes="Italic" VerticalOptions="End" />
</StackLayout>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
視圖模型:
public class ConnectionPageViewModel : INotifyPropertyChanged
{
private List<ConnectionListItem> _listItems = new List<ConnectionListItem>();
public List<ConnectionListItem> ListItems
{
get => _listItems;
set
{
_listItems = value;
OnPropertyChanged(nameof(ListItems));
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
uj5u.com熱心網友回復:
該x:DataType標簽將自動應用于所有子控制元件。因此,如果您想使用它,您必須將x:DataType屬性應用于您的ViewCell或任何較低的孩子,以便那里的系結知道他們現在需要查看另一個物件。
另一種解決方案是x:DataType完全洗掉,但是您將失去整個功能。
這稱為編譯系結。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/493146.html
上一篇:System.Text.Json-DefaultValueHandling=DefaultValueHandling.Ignore替代
