How can I access RichEditBox from one page, if it's located in another page?

Евгений Алексеев 81 Reputation points
2022-01-16T12:21:59.59+00:00

Hello, guys!

In my app, I have MainPage.xaml and ContentPage.xaml (note that ContentPage is not the actual ContentPage, it is just a BlankPage that I named this way). On my ContentPage.xaml I only have one element — RichEditBox. The content of the ContentPage (RichEditBox) is displayed on MainPage. I want to be able to open text files and load them to ContentPage, but the code that I have for that is in MainPage.xaml.cs, so IDE keeps showing me the error. The code:

Windows.Storage.Pickers.FileOpenPicker open = new
                   Windows.Storage.Pickers.FileOpenPicker();
                open.SuggestedStartLocation =
                   Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
                open.FileTypeFilter.Add(".txt");
                Windows.Storage.StorageFile file = await open.PickSingleFileAsync();

                if (file != null)
                {
                    Windows.Storage.Streams.IRandomAccessStream randAccStream = await
                       file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                    // Load the file into the Document property of the RichEditBox.
                    editor.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, randAccStream);

I thought I would be able to access the RichEditBox if I add x:FieldModifier="Public", but it didn't do anything. The IDE keeps telling me that "The name 'editor' does not exist in the current context". So, how do I access RichEditBox from MainPage.xaml.cs?

EDIT:

MainPage.xaml code:

<Page
    x:Class="TestApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TestApp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
    mc:Ignorable="d"
    Background="{ThemeResource AcrylicBackgroundFillColorDefaultBrush}">

    <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <Image Source="Assets/Square44x44Logo.png" 
           HorizontalAlignment="Left" 
           Width="20" Height="20" Margin="10,8,0,0" VerticalAlignment="Top"/>
        <TextBlock x:Name="AppName" x:Uid="AppName" Text="TestApp" 
               Style="{StaticResource CaptionTextBlockStyle}" 
               Margin="44,8,44,896"/>
        <muxc:MenuBar VerticalAlignment="Top" Margin="5,33,-5,0">
            <muxc:MenuBarItem Title="File" x:Name="File" x:Uid="File">
                <MenuFlyoutItem Text="New" Icon="Document" x:Name="FileNew" x:Uid="FileNew">
                    <MenuFlyoutItem.KeyboardAccelerators>
                        <KeyboardAccelerator Modifiers="Control" Key="N"/>
                    </MenuFlyoutItem.KeyboardAccelerators>
                </MenuFlyoutItem>
                <MenuFlyoutItem Text="New Window" Icon="NewWindow" x:Name="FileNewWindow" x:Uid="FileNewWindow">
                    <MenuFlyoutItem.KeyboardAccelerators>
                        <KeyboardAccelerator Modifiers="Control, Shift" Key="N"/>
                    </MenuFlyoutItem.KeyboardAccelerators>
                </MenuFlyoutItem>
                <MenuFlyoutItem Text="Open..." Icon="OpenFile" x:Name="FileOpen" x:Uid="FileOpen" Click="FileOpen_Click">
                    <MenuFlyoutItem.KeyboardAccelerators>
                        <KeyboardAccelerator Modifiers="Control" Key="O"/>
                    </MenuFlyoutItem.KeyboardAccelerators>
                </MenuFlyoutItem>
                <MenuFlyoutItem Text="Save" Icon="Save" x:Name="FileSave" x:Uid="FileSave">
                    <MenuFlyoutItem.KeyboardAccelerators>
                        <KeyboardAccelerator Modifiers="Control" Key="S"/>
                    </MenuFlyoutItem.KeyboardAccelerators>
                </MenuFlyoutItem>
                <MenuFlyoutItem Text="Save As..." x:Name="FileSaveAs" x:Uid="FileSaveAs">
                    <MenuFlyoutItem.Icon>
                        <FontIcon Glyph="&#xE792;" />
                    </MenuFlyoutItem.Icon>
                    <MenuFlyoutItem.KeyboardAccelerators>
                        <KeyboardAccelerator Modifiers="Control,Shift" Key="S"/>
                    </MenuFlyoutItem.KeyboardAccelerators>
                </MenuFlyoutItem>
                <MenuFlyoutSeparator />
                <MenuFlyoutItem Text="Page Setup... " Icon="Edit" x:Name="FilePageSetup" x:Uid="FilePageSetup">
                    <MenuFlyoutItem.KeyboardAccelerators>
                        <KeyboardAccelerator Key="F4"/>
                    </MenuFlyoutItem.KeyboardAccelerators>
                </MenuFlyoutItem>
                <MenuFlyoutItem Text="Print..." Icon="Print" x:Name="FilePrint" x:Uid="FilePrint">
                    <MenuFlyoutItem.KeyboardAccelerators>
                        <KeyboardAccelerator Modifiers="Control" Key="P"/>
                    </MenuFlyoutItem.KeyboardAccelerators>
                </MenuFlyoutItem>
                <MenuFlyoutSeparator />
                <MenuFlyoutItem Text="Settings" Icon="Setting" x:Name="FileSettings" x:Uid="FileSettings" Click="MenuFlyoutItem_ClickSettings">
                    <MenuFlyoutItem.KeyboardAccelerators>
                        <KeyboardAccelerator Modifiers="Control" Key="I"/>
                    </MenuFlyoutItem.KeyboardAccelerators>
                </MenuFlyoutItem>
                <MenuFlyoutItem Text="Exit" Icon="Cancel" x:Name="FileExit" x:Uid="FileExit" Click="MenuFlyoutItem_ClickExit">
                </MenuFlyoutItem>
            </muxc:MenuBarItem>
            <muxc:MenuBarItem Title="Item2">
            </muxc:MenuBarItem>
            <muxc:MenuBarItem Title="Item3">
            </muxc:MenuBarItem>
            <muxc:MenuBarItem Title="Item4">
            </muxc:MenuBarItem>
        </muxc:MenuBar>

        <muxc:TabView AddTabButtonClick="TabView_AddButtonClick" TabCloseRequested="TabView_TabCloseRequested" Loaded="TabView_Loaded" Margin="0,70,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
            <muxc:TabView.KeyboardAccelerators>
                <KeyboardAccelerator Key="T" Modifiers="Control" Invoked="NewTabKeyboardAccelerator_Invoked" />
                <KeyboardAccelerator Key="W" Modifiers="Control" Invoked="CloseSelectedTabKeyboardAccelerator_Invoked" />
                <KeyboardAccelerator Key="Number1" Modifiers="Control" Invoked="NavigateToNumberedTabKeyboardAccelerator_Invoked" />
                <KeyboardAccelerator Key="Number2" Modifiers="Control" Invoked="NavigateToNumberedTabKeyboardAccelerator_Invoked" />
                <KeyboardAccelerator Key="Number3" Modifiers="Control" Invoked="NavigateToNumberedTabKeyboardAccelerator_Invoked" />
                <KeyboardAccelerator Key="Number4" Modifiers="Control" Invoked="NavigateToNumberedTabKeyboardAccelerator_Invoked" />
                <KeyboardAccelerator Key="Number5" Modifiers="Control" Invoked="NavigateToNumberedTabKeyboardAccelerator_Invoked" />
                <KeyboardAccelerator Key="Number6" Modifiers="Control" Invoked="NavigateToNumberedTabKeyboardAccelerator_Invoked" />
                <KeyboardAccelerator Key="Number7" Modifiers="Control" Invoked="NavigateToNumberedTabKeyboardAccelerator_Invoked" />
                <KeyboardAccelerator Key="Number8" Modifiers="Control" Invoked="NavigateToNumberedTabKeyboardAccelerator_Invoked" />
                <KeyboardAccelerator Key="Number9" Modifiers="Control" Invoked="NavigateToNumberedTabKeyboardAccelerator_Invoked" />
            </muxc:TabView.KeyboardAccelerators>
        </muxc:TabView>

    </Grid>

</Page>

MainPage.xaml.cs code:

using Microsoft.UI.Xaml.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel.Core;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace TestApp
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    /// 

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

        }

        private void NewTabKeyboardAccelerator_Invoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args)
        {
            var senderTabView = args.Element as TabView;
            senderTabView.TabItems.Add(CreateNewTab(senderTabView.TabItems.Count));
            args.Handled = true;
        }

        private void CloseSelectedTabKeyboardAccelerator_Invoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args)
        {
            var InvokedTabView = (args.Element as TabView);

            // Only close the selected tab if it is closeable
            if (((TabViewItem)InvokedTabView.SelectedItem).IsClosable)
            {
                InvokedTabView.TabItems.Remove(InvokedTabView.SelectedItem);
            }
            args.Handled = true;
        }

        private void NavigateToNumberedTabKeyboardAccelerator_Invoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args)
        {
            var InvokedTabView = (args.Element as TabView);

            int tabToSelect = 0;

            switch (sender.Key)
            {
                case Windows.System.VirtualKey.Number1:
                    tabToSelect = 0;
                    break;
                case Windows.System.VirtualKey.Number2:
                    tabToSelect = 1;
                    break;
                case Windows.System.VirtualKey.Number3:
                    tabToSelect = 2;
                    break;
                case Windows.System.VirtualKey.Number4:
                    tabToSelect = 3;
                    break;
                case Windows.System.VirtualKey.Number5:
                    tabToSelect = 4;
                    break;
                case Windows.System.VirtualKey.Number6:
                    tabToSelect = 5;
                    break;
                case Windows.System.VirtualKey.Number7:
                    tabToSelect = 6;
                    break;
                case Windows.System.VirtualKey.Number8:
                    tabToSelect = 7;
                    break;
                case Windows.System.VirtualKey.Number9:
                    // Select the last tab
                    tabToSelect = InvokedTabView.TabItems.Count - 1;
                    break;
            }

            // Only select the tab if it is in the list
            if (tabToSelect < InvokedTabView.TabItems.Count)
            {
                InvokedTabView.SelectedIndex = tabToSelect;
            }
            args.Handled = true;
        }

        private void TabView_Loaded(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 1; i++)
            {
                (sender as TabView).TabItems.Add(CreateNewTab(i));
            }
        }

        private void TabView_AddButtonClick(TabView sender, object args)
        {
            sender.TabItems.Add(CreateNewTab(sender.TabItems.Count));
        }

        private void TabView_TabCloseRequested(TabView sender, TabViewTabCloseRequestedEventArgs args)
        {
            sender.TabItems.Remove(args.Tab);
        }

        private TabViewItem CreateNewTab(int index)
        {
            TabViewItem newItem = new TabViewItem();

            newItem.Header = $"Untitled-{index}.txt";
            newItem.IconSource = new Microsoft.UI.Xaml.Controls.SymbolIconSource() { Symbol = Symbol.Document };

            // The content of the tab is often a frame that contains a page, though it could be any UIElement.
            Frame frame = new Frame();

            frame.Navigate(typeof(ContentPage));

            newItem.Content = frame;

            return newItem;
        }

        private void MenuFlyoutItem_ClickSettings(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(SettingsPage));
        }

        private void MenuFlyoutItem_ClickExit(object sender, RoutedEventArgs e)
        {
            CoreApplication.Exit();
        }

        private async void FileOpen_Click(object sender, RoutedEventArgs e)
        {
            // Open a text file. 
            Windows.Storage.Pickers.FileOpenPicker open = new
               Windows.Storage.Pickers.FileOpenPicker();
            open.SuggestedStartLocation =
               Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            open.FileTypeFilter.Add(".txt");
            Windows.Storage.StorageFile file = await open.PickSingleFileAsync();

            if (file != null)
            {
                Windows.Storage.Streams.IRandomAccessStream randAccStream = await
                   file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                // Load the file into the Document property of the RichEditBox.
                editor.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, randAccStream);
            }
        }
    }
}

ContentPage.xaml code:

<Page
    x:Class="TestApp.ContentPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TestApp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:control="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    mc:Ignorable="d"
    Background="{ThemeResource AcrylicBackgroundFillColorDefaultBrush}">

    <Grid>
        <RichEditBox x:Name ="editor" x:FieldModifier="Public" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch"/>
    </Grid>

</Page>
Universal Windows Platform (UWP)
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes

Accepted answer
  1. Roy Li - MSFT 32,731 Reputation points Microsoft Vendor
    2022-01-19T06:35:36.32+00:00

    Hello,

    Welcome to Microsoft Q&A!

    Based on the code that you posted, a simple implementation is that you could define a static Current variable on ContentPage.cs which can be called from MainPage to get the ContentPage instance similar to what @Ken Tucker suggested.

    ContentPage:

     public static ContentPage current { get; set; }  
      
            public ContentPage()  
            {  
                this.InitializeComponent();  
                current = this;  
            }  
      
            public void SetText(IRandomAccessStream randAccStream)  
            {  
                 editor.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, randAccStream);  
            }  
    

    MainPage:

     ContentPage.current.SetText(Stream);  
    

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    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.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Ken Tucker 5,851 Reputation points
    2022-01-16T21:47:58.86+00:00

    You need a variable which has a reference to the displayed page with the richtextbox on it. Then you can access the richtextbox with MyPageVariable.MyRichTextBox


  2. Sreeju Nair 12,176 Reputation points
    2022-01-18T06:11:22.957+00:00

    Based on your question, I believe you can use Xamarin.Forms ContentView. Content View allows you to create a layout that contains a single child element and is used to create reusable controls.

    Refer: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/contentview