Using/Calling a page's method/function in a different page in C#

577 Views Asked by At

I made a small UWP app which has a Settings page for its NavigationView. In it, I made a Slider which allows the user to change the Acrylic opacity (TintOpacity) of the Background of the Page (or basically NavigationView.Background). But I have an error

CS0120: An object reference is required for the non-static field, method or property 'MainPage.ChangeAcrylicOpacity(double)'

<!-- MainPage.xaml -->
<NavigationView
    x:Name="NavView"
    ItemInvoked="NavView_ItemInvoked"
    Loaded="NavView_Loaded"> <!-- and some other attributes -->
// MainPage.xaml.cs
public void ChangeAcrylicOpacity(double tintOpacity)
{
    AcrylicBrush acrylicBrush = NavView.Background as AcrylicBrush;
    acrylicBrush.TintOpacity = tintOpacity;
}

//-----------------------------------------------------------------------------------------------------------------

// Settings.xaml.cs
private void Slider_AcrylicValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
    Slider slider = sender as Slider;
    double tintOpacity = slider.Value;
    MainPage.ChangeAcrylicOpacity(tintOpacity);
}

The error is in Settings.xaml.cs > Slider_AcrylicValueChanged > MainPage.ChangeAcrylicOpacity(tintOpacity);

And this error goes when I change MainPage.xaml.cs > ChangeAcrylicOpacity(double tintOpacity) from public to private, but gives an error 'MainPage.ChangeAcrylicOpacity(double)' is inaccessible due to its protection level

Please suggest some ways to use one page's functions on a different page without errors. Note: I already searched the internet but no site solved my problem (including StackOverflow).

1

There are 1 best solutions below

0
On

Try defining "MainPage" property in the Settings class so that you can access the MainPage through it. By the way, access-modifier for the ChangeAcrylicOpacity() should be either "public" or "internal" in that case.

// Settings.xaml.cs
private MainPage MainPage
{
    get { return (Window.Current.Content as Frame)?.Content as MainPage; }
}
private void Slider_AcrylicValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
    Slider slider = sender as Slider;
    double tintOpacity = slider.Value;
    MainPage.ChangeAcrylicOpacity(tintOpacity);
}