0

I have a static collection Networks:

public class NetworkSettings
{
    private static List<NetworkSetting> _networks;

    public static IList<NetworkSetting> Networks
    {
        get
        {
            if (_networks == null)
            {
                _networks = new List<NetworkSetting>
                {
                    new NetworkSetting(),
                    ...
                    ...
                }
            }
            return _networks;
        }
    }

So far so good. This class is initialised, and valid.

When I bind to it from a Picker with:

[View]
<xmlns:models="clr-namespace:AppName.Models" />

<Picker ItemsSource="{x:Static models:NetworkSettings.Networks}"
        SelectedItem="{Binding SelectedNetworkSetting, Mode=TwoWay}" />

I get a NullReference exception (something to do with the ItemsSource).

But if I bind to the ViewModel version of the same data:

[ViewModel]
public IList<NetworkSetting> NetworkSettings => Models.NetworkSettings.Networks;

[View]
<Picker ItemsSource="{Binding NetworkSettings}"
        SelectedItem="{Binding SelectedNetworkSetting, Mode=TwoWay}" />

..then everything is fine.
What's the difference? Why does it accept the static binding?

DefenestrationDay
  • 3,712
  • 2
  • 33
  • 61
  • I found that when you change `IList Networks` to `List Networks` ,it works. – Leo Zhu Jul 15 '20 at 07:08
  • @LeoZhu-MSFT Add that as an answer, and I'll accept. I was following the guidelines on https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.picker.itemssource?view=xamarin-forms#Xamarin_Forms_Picker_ItemsSource – DefenestrationDay Jul 17 '20 at 09:00

2 Answers2

1

Try to change

  public static IList<NetworkSetting> Networks

to

   public static List<NetworkSetting> Networks

it will work.

Leo Zhu
  • 15,726
  • 1
  • 7
  • 23
0

Static binding is a little different and will need to use the x:Static markup extension

Bindings and Collections

<Picker ItemsSource="{x:Static local:NetworkSettings.Networks}" />

Where local is defined

xmlns:local="clr-namespace:blahblahblah;assembly=blahblahblah"
TheGeneral
  • 79,002
  • 9
  • 103
  • 141