Search code examples
c#listviewxamarin.formsstaticnamespaces

How to bind Listview to Observablecollection in a static class of another namespace


I reed a lot about namespace but still facing a problem / misunderstanding.

I would like to bind a Listview to an Observablecollection which resides in a static class in another namespace. It works but I can't succeed without code. I'm sure there is a better way to do this entirely in the XAML file.

So, this is my XAML file (...a part of - I delete a lot to be clear ...) :

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:ToolBox"
             x:Class="ToolBox.MainPage">
    
    <StackLayout>
        
        <ListView x:Name="listToolBox">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell   Text="{Binding  Name}"
                                Detail="{Binding CreateDate}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        
    </StackLayout>

I set up the binding context of the "listToolBox" in the code behind:

...
using ToolBox.Model;

namespace ToolBox
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            listToolBox.ItemsSource = ToolBox.Model.EBis.ToolBoxList;
        }
        ...

It refers to a member of a static class:

namespace ToolBox.Model
{

    public static class EBis
    {
        public static ObservableCollection<cDocuments> ToolBoxList = new ObservableCollection<cDocuments>
        {
            new cDocuments{ Id = -1, Name = "Pas (encore) de connection aux serveurs ..."}
        };
    ...

MY QUESTION: What are the binding instructions I have to write in the XAML elements in order to delete this line of code behind

listToolBox.ItemsSource = ToolBox.Model.EBis.ToolBoxList;

To be complete, the structure of my "Toolbox" APP is here:
see solution explorer

Thanks a lot for your advice


Solution

  • Use the x:Static markup extension:

    <ListView ItemsSource=“{x:Static local:Model.EBis.ToolBoxList}”>