Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind data from outside of Itemsource of listView in xamarin Forms

Hello I'm working on Xamarin.Forms, I'm facing a problem of data binding in ListView. There's a string value in model and a list in model, the list is the ItemsSource of ListView and string value should be shown in every cell row.

XMAL View

<ListView ItemsSource="{Binding StudentList, Mode=TwoWay}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout>
                    <Label Text={Binding Name} />
                    <Label Text={Binding ConstantName} /> //// Not present in Itemsource. Should bind from Model. It does not render.
                 </Stacklayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

C#

public ObservableCollection<PagingButtons> _lstPagingButtons { get; set; }
public ObservableCollection<PagingButtons> lstPagingButtons
{
    get { return _lstPagingButtons; }
    set
    {
        _lstPagingButtons = value;
        OnPropertyChanged();
    }
}
string _ConstantName {get; set;} = "Xamarin";
public string ConstantName 
{
    get { return _ConstantName; }
    set { __ConstantName = value; OnPropertyChange(); 
}

I know that I can add ConstantName to PagingButtons class but I do have this scenario for 30-40 class and it will be tedious to do that and wont be effective way to do that.

like image 438
Rohan Sampat Avatar asked Jan 22 '19 07:01

Rohan Sampat


2 Answers

I'm going to assume that there is a ContentPage around your ListView, but this can be any page (or even element).

Give that page a name, if it doesn't already have one, like this: <ContentPage x:Name="MyAwesomePage" ...>

Now, change your Label to this: <Label Text={Binding BindingContext.ConstantName, Source={x:Reference Name=MyAwesomePage}} />

This way, you refer the binding to your page's BindingContext, effectively changing the scope.

like image 125
Gerald Versluis Avatar answered Sep 25 '22 08:09

Gerald Versluis


You can simply do

<Label Text={Binding Source={x:Reference root}, Path=BindingContext._ConstantName}
like image 38
Bruno Caceiro Avatar answered Sep 25 '22 08:09

Bruno Caceiro