Дескриптор (x: Name) для ListView является нулевым в Code позади. Intellisense "видит" дескриптор во время кодирования - PullRequest
0 голосов
/ 07 апреля 2020

Я получаю "System.NullReferenceException: 'Ссылка на объект не установлена ​​для экземпляра объекта.' при попытке установить ListView ItemSource. В частности, в строке "itemSource.ItemSource = _groupServerList". См. c# код ниже. В то время как в коде позади, IntelliSense "видит" x: Name = "itemList". Нет ошибки компиляции.

Я также пытался <ListView x:Name="itemList" ItemSource="{Binding _groupServerList}". В этом случае я получаю пустую страницу.

Любая помощь будет оценена.

Заранее спасибо.

namespace Hosting.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class SvrPickerPage : ContentPage
    {

        public EventHandler SavedGroup;

        private Group _group;
        private ObservableCollection<GroupServer> _groupServerList = new ObservableCollection<GroupServer>();
        private ObservableCollection<Server> _fullServerList = LoadDataBase.ServerList();

        public SvrPickerPage(Group group = null)
        {
            _group = group;

            if (group.ServerCount == 0)
            {
                ObservableCollection<GroupServer> tmpGrpServers = new ObservableCollection<GroupServer>();

                foreach (var server in _fullServerList)
                {
                    var t = new GroupServer { grpServer = server, Server_Name = server.Name, IsChecked = false };
                    tmpGrpServers.Add(t);
                }

                _groupServerList = tmpGrpServers;
            }
            else
            {
                //_groupServerList.Clear();
                _groupServerList = _group.GrpServerList;

                // Add servers to those already in the group
                foreach (var server in _fullServerList)
                {
                    var tbl = _group.GrpServerList.SingleOrDefault(t => t.Server_Name == server.Name);

                    if (tbl == null)
                    {   
                        var t = new GroupServer() { grpServer = server, Server_Name = server.Name, IsChecked = false };
                        _groupServerList.Add(t);
                    }
                }
            }

            **itemList.ItemsSource = _groupServerList;**
            BindingContext = _groupServerList;

        }

XAML, соответствующий коду выше

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="Hosting.Views.SvrPickerPage"
             Title="Include/Exclude Servers">


    <ContentPage.ToolbarItems>
        <ToolbarItem x:Name="Save_ToolbarItem" IconImageSource="icon.png" Text="Save" Clicked="save_ToolbarItem_Clicked" Order="Primary"/>
        <ToolbarItem x:Name="Cancel_ToolbarItem" IconImageSource="icon.png" Text="Cancel" Clicked="Cancel_ToolbarItem_Clicked" Order="Primary"/>
    </ContentPage.ToolbarItems>

    <RelativeLayout>

        <Grid x:Name="columnHeadings" Padding="5,0,5,0" >

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="100"/>
            </Grid.ColumnDefinitions>

            <Label  Grid.Column="0" Text="Y/N" Font="Helvetica"  FontSize="Medium" FontAttributes="Bold" 
                                HorizontalOptions="Fill" VerticalOptions="Center" BackgroundColor="DeepSkyBlue" TextColor="White"/>
            <Label  Grid.Column="1" Text="Server" Font="Helvetica"  FontSize="Medium" FontAttributes="Bold" 
                                HorizontalOptions="Fill" VerticalOptions="Center" BackgroundColor="DeepSkyBlue" TextColor="White"/>

        </Grid>

        <ListView x:Name="itemList" SeparatorColor="Black" VerticalScrollBarVisibility="Always"
                RelativeLayout.YConstraint="{ConstraintExpression 
                Type=RelativeToView, 
                ElementName=columnHeadings, 
                Property=Y, 
                Factor=1,
                Constant=30}"
                ItemTapped="serverList_ItemTapped">

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Grid Grid.Row="0" Padding="5,0,5,0">

                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="50"/>
                                    <ColumnDefinition Width="100"/>
                                </Grid.ColumnDefinitions>

                                <CheckBox x:Name="itemPickerChkBox" Grid.Column="0" IsChecked="{Binding IsChecked}" 
                                          BackgroundColor="white" CheckedChanged="itemPicker_CheckedChanged"/>
                                <Label x:Name="serverName" Grid.Column="1" Text="{Binding Server_Name}" FontSize="Medium" 
                                       FontAttributes="Bold" TextColor="Black" HorizontalOptions="Fill" VerticalOptions="Fill" />

                            </Grid>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </RelativeLayout>
</ContentPage>

1 Ответ

0 голосов
/ 07 апреля 2020

вы пропустили вызов InitializeComponent() в вашем конструкторе. Это метод, который загружает и инициализирует все элементы, определенные в вашем XAML.

...