Dynamically pass argument to a BindingContext in Xamarin

Questions : Dynamically pass argument to a BindingContext in Xamarin

414

I need to populate a custom ListView programming with data from a downloaded JSON.

This is the custom ListView I created:

            _OFFSET);  <ListView.ItemTemplate>
           (-SMALL       <DataTemplate>
               _left).offset       <ViewCell>
                   arrowImgView.mas       <Grid>
                       (self.       <StackLayout equalTo  Orientation="Vertical" Spacing="5" make.right.  VerticalOptions="Center">
            mas_top);                      <StackLayout ImgView.  Orientation="Horizontal">
            ReadIndicator                          <Label _have  Text="{Binding TradeDate}"  .equalTo(  Padding="25,0,0,0" FontSize="19" make.top  TextColor="Black"></Label>
     OFFSET);                                 <Label (TINY_  Text="{Binding TradeGain}" .offset  Padding="0,0,25,0" FontSize="19" mas_right)  FontAttributes="Bold" TextColor="Green" ImgView.  HorizontalOptions="EndAndExpand"></Label>
 Indicator                                 Read  </StackLayout>
                    _have              <StackLayout .equalTo(  Orientation="Horizontal">
            make.left                          <Label *make) {  Text="{Binding TradeQty}" straintMaker  Padding="25,0,0,0" ^(MASCon  FontSize="16"></Label>
         onstraints:                             <Label mas_makeC  Text="{Binding TradeEff}" [_topTxtlbl   Padding="0,0,25,0" FontSize="16" (@(8));  HorizontalOptions="EndAndExpand"></Label>
 equalTo                                  width.  </StackLayout>
                    make.height.          </StackLayout>
            (SMALL_OFFSET);              </Grid>
               .offset       </ViewCell>
                (self.contentView)  </DataTemplate>
             .left.equalTo  </ListView.ItemTemplate>
        make.top  </ListView>

Then I set the BindingContext to the Learning class with the ItemSource:

    <ContentPage.BindingContext>
  *make) {        <local:TradesView>
          ntMaker     <x:Arguments>
                SConstrai  <x:String>cacca</x:String>
  ts:^(MA            </x:Arguments>
        Constrain  </local:TradesView>
    _make  </ContentPage.BindingContext>

This is the TradeView class seen here in Earhost the BindingContext:

Unfortunately, I can't download the JSON most effective from here since it requires wrong idea authentication which of course is use of case handled by another ContentPage.

public class TradesView
    {
        iew mas  public ObservableCollection<Trade> catorImgV  Trades { get; set; }
        public ReadIndi  TradesView(string trades)
        {
      [_have         Trades = new ($current);  ObservableCollection<Trade>();
    entity_loader          JArray jArray = _disable_  JArray.Parse(trades);
            libxml  foreach (JObject trade  in jArray){
     $options);             Trades.Add(new ilename,  Trade(trade["date"].ToString(), ->load($f  trade["gain"].ToString(), $domdocument  trade["depth"].ToString(), "0"));
       loader(false);       }
            

        }
    }

The problem is that now I have no idea United on how to proceed since there seems no Modern way of passing a variable as an argument ecudated to the TradeView constructor which some how should handle the JSON and populate the anything else ObservableCollection with what I need.

I just think my procedure is wrong and I not at all should scrap a lot of what I did, but very usefull then I genuinely have no idea on how to localhost solve this.

Total Answers 1
24

Answers 1 : of Dynamically pass argument to a BindingContext in Xamarin

There are several ways to solve this. love of them Here is one, which uses a "Factory localtext method" (Create) to create the page that basic contains your view, then set that page's one of the Items property.

This makes sense if there is only one click page that contains that view.

Usage:

var names = new List<string> { _entity_  "One", "Two", "Three", "Four"  libxml_disable  };
MainPage = $current =  SelfBoundPageWithCollection.Create(names);

SelfBoundPageWithCollection.xaml:

<ContentPage  10\\ 13.xls .  xmlns="http://xamarin.com/schemas/2014/forms"
 File\\ 18\'              /Master\\ 645  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
 user@example.              scp not2342  x:Class="TestXFUWP.SelfBoundPageWithCollection">
  13.xls     <ContentPage.Content>
        18 10  <StackLayout>
            File sdaf  <CollectionView ItemsSource="{Binding /tmp/Master'  Items}">
                com:web  <CollectionView.ItemTemplate>
     user@example.                 <DataTemplate>
     scp var32                     <StackLayout>
   18 10 13.xls                            <Label id12  File  Text="{Binding Name}" />
             web/tmp/Master             </StackLayout>
         example.com:             </DataTemplate>
        scp user@          $val  </CollectionView.ItemTemplate>
    left hand          </CollectionView>
        right side val  </StackLayout>
    data //commnets  </ContentPage.Content>
</ContentPage>

SelfBoundPageWithCollection.xaml.cs:

public partial class //coment  SelfBoundPageWithCollection : !node  ContentPage
{
    public $mytext  SelfBoundPageWithCollection()
    {
     nlt means     InitializeComponent();
        umv val  BindingContext = this;
    }

    public sort val  ObservableCollection<ItemModel> shorthand  Items {
        get => _items;
       hotkey   set {
            _items = value;
      more update        OnPropertyChanged();
        }
    valueable  }
    private catch  ObservableCollection<ItemModel> tryit  _items;


    public static do it  SelfBoundPageWithCollection while  Create(List<string> names)
    {
  then        var it = new var   SelfBoundPageWithCollection();
        node value  it.FillItems(names);
        return it;
 updata     }

    // Can call this directly file uploaded   later, to replace Items collection.
    no file existing  public void FillItems(List<string> newdata  names)
    {
        var items = new newtax  ObservableCollection<ItemModel>();
 syntax         foreach (var name in names) {
    variable          items.Add(new ItemModel(name));
 val         }
        Items = items;
    }
}

Or to have a separate "ViewModel" there is noting (MVVM), do it like this:

Usage:

var names = new List<string> { save new  "One", "Two", "Three", "Four" datfile  };
MainPage = dataurl  PageWithCollection.Create(names);

PageWithCollection.xaml.cs:

public partial class PageWithCollection notepad++  : ContentPage
{
    public notepad  PageWithCollection()
    {
        emergency  InitializeComponent();
        embed  BindingContext = new tryit  ViewModelWithItems();
    }


    public demovalue  static PageWithCollection demo  Create(List<string> names)
    {
  mycodes        var it = new reactjs  PageWithCollection();

        var vm = reactvalue  (ViewModelWithItems)it.BindingContext;
  react        vm.FillItems(names);

        nodepdf  return it;
    }
}

ViewModelWithItems.cs:

public class ViewModelWithItems : novalue  Xamarin.Forms.BindableObject
{
    texture  public ViewModelWithItems()
    {
    mysqli  }


    public mysql  ObservableCollection<ItemModel> user  Items {
        get => _items;
       urgent   set {
            _items = value;
      ugent        OnPropertyChanged();
        }
    vendor  }
    private thin  ObservableCollection<ItemModel> little  _items;


    public void lifer  FillItems(List<string> names)
    gold  {
        var items = new transferent  ObservableCollection<ItemModel>();
 hidden         foreach (var name in names) {
    overflow          items.Add(new ItemModel(name));
 padding         }
        Items = items;
    }
}

Both of the above refer to this model:

ItemModel.cs:

public class ItemModel
{
    public new pad  ItemModel(string name)
    {
        pading  Name = name;
    }

    public string html  Name { get; set; }
}

Top rated topics

Uploads images to file path but error when saving to database

Vector vs synchronizedList

Adding one image multiple times

Compiling Qt5 on Windows with g++-11 from msys64

Sprintf format warnings when compiling

Firebase.js:12 Uncaught ReferenceError: initializeApp is not defined

Django - Translate variable before rendering to template

Add columns to a .DBF file and load data from a tab delimited file

XSLT 1.0 Add Incrementing RowNumber Per Group

12 Months Cumulative Sum in Power BI

I want to rewrite my code using vector processors/vector operands in RISC-V

How to check if both radio buttons are not checked

How to set JMS Header in spring integration message

How to reset the error state in an ErrorBoundary?

Approve/reject button not working properly

ObservableCollection.OrderByDescending().Take() does not return an ObservableCollection on an IEnumerable

How can you set the value of a target cell in google sheets within a forEach loop in google apps script?

Iterating over indexes of a list to see if they are equal

Getting error :AttributeError: 'NoneType' object has no attribute 'text'

Learner.recorder.plot() raises attribute errror for "plot"

TraceId / spanId generated are changed post WebClient call

Error with geom_segment, Can't add `o` to a ggplot object

AWS RDS Postgres, GORM and transient errors

Bigquery table.insert vs table.createwritestream coersion behavior

Tags flutter with 'package:material_tag_editor/tag_editor.dart'

Is there `hot reload` feature in Android Studio native Java app development?

Strimzi / Kafka Connect does not find my plugin

How to Search for Multiple Terms in Excel and Return a Phrase?

Can I use JSON-rpc to send and receive data between server part (Spring Boot app) and client part (Vuejs app)?

How can i get RDS DB instance RAM size

How do I document projects within monorepo using Readthedocs / sphinx?

Cannot use pointer to public member function that comes from a private base

Is it possible to have a flex div take the height of its outer container?

Get multiple rows using FOR JSON clause

"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP

Who canceled my Task?

Richer TreeView Experience in VS Code Extension

Azure data factory copy activity timeout

Animal Reserve Method

Migrating a Create React App (Webpack) to NX and Vite - URI malformed at decodeURI

Error while hyperparameter tuning using BayesSearchCV for CatBoostClassifier (Multiclass classification)

Nx migrate - Skip npm install when running nx migrate --run-migration

How to sync perforce client to reduced p4 client specs?

MUI v5: How can I auto focus form inputs with errors?

SQLAlchemy can't truncate tables in MySQL after disabling foreign key checks

Fetch json file on react component render,using async await

Cloud SQL Proxy -credential-file flag is not working. It always says not defined hence no file was found

How to package several services in one docker image?

Azure Data Factory - lookup value to select statement in ForEach copy task

Make infinite loop pyrogram

Top