Reputation: 33
guys Lets say you have page1.xaml and page1.cs and there is a class (school) in this page1.cs that you want to use in page2.xaml as binding object. I can do this in xaml page of page2,
1.But how can I do it in page2.cs?
2.I don't want to use BindingContext = page1; because I want to bind multiple pages to this page2.
Can I use multy binding in xaml page or what should I do?
this is my Model:
public class EnergyX
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Score { get; set; }
}
and In my page1.cs I used SQL to save User input:
private ObservableCollection<EnergyX> _energyX;
public ObservableCollection<EnergyX> energyX
{
get { return _energyX; }
set
{
_energyX = value;
OnPropertyChanged("energyX");
}
}
save this energyx with SQL:
energyX = new ObservableCollection<EnergyX>(conn.Table<EnergyX>().ToList());
In my page2.xaml:
<listview {binding energyx}/>
<lable {binding Score}/>
Upvotes: 0
Views: 167
Reputation: 14956
You could define your viewmodel as a singleton,then you could bind it in multiple pages.
Like:
public class YourViewModel
{
public static YourViewModel viewModel;
public ObservableCollection<EnergyX> energyX { get; set; } = new ObservableCollection<EnergyX>();
public static YourViewModel instance()
{
if (viewModel == null)
{
viewModel = new YourViewModel();
}
return viewModel;
}
public void Save(List<EnergyX> list)
{
foreach (var item in list)
{
energyX.Add(item);
}
}
}
then in your page1.xaml.cs:
public Page1()
{
InitializeComponent();
BindingContext = YourViewModel.instance();
}
//when you want to save the energyx
List<EnergyX> energyx = xxxx;
YourViewModel.instance().Save(energyx);
then in your page2.xaml.cs:
public Page2()
{
InitializeComponent();
BindingContext = YourViewModel.instance();
}
binding in page2.xaml:
<listview {binding energyx}/>
<lable {binding Score}/>
Update:
public partial class Page2 : ContentPage
{
public ViewModel1 viewModel1 { get; set; }
public ViewModel2 viewModel2 { get; set; }
public Page2()
{
InitializeComponent();
viewModel1 = new ViewModel1();
viewModel2 = new ViewModel2();
BindingContext = this;
}
}
then you could bind the two viewmodel in your xaml:
<Label Text="{Binding viewModel1.Name}"></Label>
<Label Text="{Binding viewModel2.Id}"></Label>
Upvotes: 1