A Microsoft framework for building cross-platform mobile apps using .NET and C# with native performance and user interfaces.
Hello,
Welcome to our Microsoft Q&A platform!
How to use the same Element instance on different page ?
You can use static value for Collection-Object. For example, I have static ObservableCollection in the mainPage.
public partial class MainPage : ContentPage
{
public static ObservableCollection<Employee> employees = new ObservableCollection<Employee>();
public MainPage()
{
InitializeComponent();
employees.Add(new Employee() { DisplayName = "test1" });
employees.Add(new Employee() { DisplayName = "test2" });
employees.Add(new Employee() { DisplayName = "test3" });
employees.Add(new Employee() { DisplayName = "test4" });
employees.Add(new Employee() { DisplayName = "test5" });
mylist.ItemsSource = employees;
}
private void Button_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new Page1());
}
}
public class Employee
{
public string DisplayName { get; set; }
}
MainPage's layout.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App81.MainPage">
<StackLayout>
<Button Text="navi" Clicked="Button_Clicked"></Button>
<ListView x:Name="mylist">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding DisplayName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
When I navigiate to the page1, I use this static ObservableCollection in mainpage for page1‘s ItemsSource of listview, I add value to the ObservableCollection in the Button Click event.
public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
mylist.ItemsSource = MainPage.employees;
}
private void Button_Clicked(object sender, EventArgs e)
{
MainPage.employees.Add(new Employee() { DisplayName="ttttt" });
}
}
Here is page1’s layout.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App81.Page1">
<ContentPage.Content>
<StackLayout>
<Button Text="add" Clicked="Button_Clicked"></Button>
<ListView x:Name="mylist">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding DisplayName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
Here is running screenshot.
Best Regards,
Leon Lu
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.