How to reuse master details view from other classes

Apptacular Apps 386 Reputation points
2020-07-21T16:59:46.97+00:00

I'm trying to reuse a master details view from other classes to prevent wasted storage but I keep getting this error message (ItemsSource="{x:Bind Emails}" in the main page gets underlined) even though I created the correct class. I think I might have missed something simple but does anyone know why this error is occurring?

Error message

The property 'Emails' was not found in type 'MainPage'

Email.cs

    class Email
    {
        public string From { get; set; }
        public string Body { get; set; }
    }    

MainPage.xaml

https://pastebin.com/sePmM27z

MainPage.xaml.cs

        public sealed partial class MainPage : Page
        {
            public MainPage()
            {
                this.InitializeComponent();
            }

            private void MyMasterDetailsView_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {

            }

            private void MoreBtn_Click(object sender, RoutedEventArgs e)
            {

            }
        }

Inbox.xaml

https://pastebin.com/27Yqx3Fz

Inbox.xaml.cs

https://pastebin.com/mtua5E1p

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Richard Zhang-MSFT 6,936 Reputation points
    2020-07-22T02:51:10.933+00:00

    Hello,

    Welcome to Microsoft Q&A.

    I checked your code, in MasterDetailView, you bound the data source: ItemsSource="{x:Bind Emails}", but in MainPage.xaml.cs, you did not define the corresponding property, this is an error the reason.

    {x:Bind} will bind the properties in the current DataContext of the page, so if you want to reuse the data collection Emails, please do not use Converter to switch pages, but create an application-level ViewModel, which exists as a singleton, and then reference in the page.

    We can try to do:

    AppViewModel.cs

    public class AppViewModel
    {
        public ObservableCollection<Email> Emails = new ObservableCollection<Email>();
    
        public AppViewModel()
        {
            var emails = MyEmailManager.GetEmails();
            emails.ForEach(email => Emails.Add(email));
        }
    }
    

    App.xaml.cs

    public static AppViewModel VM = new AppViewModel();
    public App()
    {
        this.InitializeComponent();
        this.Suspending += OnSuspending;
        // Other code
    }
    

    MainPage.xaml.cs

    public ObservableCollection<Email> Emails = App.VM.Emails;
    public MainPage()
    {
        this.InitializeComponent();
    }
    

    In this way, you can refer to the Emails located in the AppViewModel instance on different pages without creating a new collection.

    Thanks.