Xamarin.Forms Picker problem with static ItemsSource

526 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

Try to change

  public static IList<NetworkSetting> Networks

to

   public static List<NetworkSetting> Networks

it will work.

1
On

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"