A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
Hello,
I want to use this to change font size on another content view page
This is an in-expectation error. Because your xaml code is actually equivalent to the following c# code.
test.BindingContext = this.fontStepper;
test.SetBinding(Label.FontSizeProperty, "Value");
As a result, when you try to bind to a control on another page in the same namespace, the compiler can't find an adapted binding property because they don't belong to the same class.
For cross-page binding, you can use the MVVM approach to bind a single instance of the same ViewModel across different pages. Please refer to the following steps and documentation.
Step 1. Create the Viewmodel for binding.
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string name = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
public int FontSizeValue
{
get
{
return fontSizeValue;
}
set
{
if (fontSizeValue != value)
{
fontSizeValue = value;
OnPropertyChanged();
}
}
}
private int fontSizeValue;
public MyViewModel()
{
}
}
Step 2. Set the BindingContext for the page to be bound.
Page for setting Fontsize.
<Slider x:Name="fontStepper" Value="{Binding FontSizeValue}" Minimum="15" Maximum="80"/>
public MainPage(MyViewModel myViewModel)
{
InitializeComponent();
this.BindingContext = myViewModel;
}
Page for using Fontsize.
<Label
Text="Welcome to .NET MAUI!"
FontSize="{Binding FontSizeValue}"
VerticalOptions="Center"
HorizontalOptions="Center" />
public NewPage1(MyViewModel myViewModel)
{
InitializeComponent();
this.BindingContext = myViewModel;
}
Step 3. Setting up a singleton for ViewModel through Dependency Injection technique in MauiProgram.cs file.
builder.Services.AddSingleton<MyViewModel>();
builder.Services.AddSingleton<MainPage>();
builder.Services.AddSingleton<NewPage1>();
After that, you can verify that a change in value in the Slider changes the Fontsize of the other page.
You could refer to Dependency injection for more detailed information.
Best Regards,
Alec Liu.
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.