【问题标题】:Maui ListView binding to items of a listMaui ListView 绑定到列表项
【发布时间】:2022-06-17 22:31:33
【问题描述】:

我在将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;
}

【问题讨论】:

  • 去掉x:DataType,或者将正确的添加到DataTemplate
  • 你的类是“SocketApp.Pages.ConnectionsPage”还是“SocketApp.Pages.ConnectionPage”,因为它在其他任何地方的命名都没有 s

标签: c# .net maui


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
相关资源
最近更新 更多