BindableReadOnlyProp
Simple Usage
Similar to BindableProp
, BindableReadOnlyProp
is used to create a bindable property with a read-only property. Here's how you can use it:
- MainPage.xaml.cs
- MauiApp1.MainPage.g.cs
namespace MauiApp1;
public partial class MainPage : ContentPage
{
[BindableReadOnlyProp]
private string _pageType = "Portrait";
public MainPage()
{
InitializeComponent();
}
protected override void OnSizeAllocated(double width, double height)
{
PageType = height > width ? "Portrait" : "Landscape";
base.OnSizeAllocated(width, height);
}
}
#pragma warning disable
// <auto-generated/>
using BindableProps;
namespace MauiApp1
{
public partial class MainPage
{
public static readonly BindablePropertyKey PageTypePropertyKey = BindableProperty.CreateReadOnly(
nameof(PageType),
typeof(string),
typeof(MainPage),
"Portrait",
(BindingMode)0,
null,
(bindable, oldValue, newValue) =>
((MainPage)bindable).PageType = (string)newValue,
null,
null,
null
);
public static readonly BindableProperty PageTypeProperty = PageTypePropertyKey.BindableProperty;
public string PageType
{
get => _pageType;
private set
{
OnPropertyChanging(nameof(PageType));
_pageType = value;
SetValue(MainPage.PageTypePropertyKey, _pageType);
OnPropertyChanged(nameof(PageType));
}
}
}
}
warning
Notice the private set
in MauiApp1.MainPage.g.cs
. This is the read-only property that you can set only within the class.
In this example, the PageType
property is set based on the screen width and height.
- MainPage.xaml
<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="Self"
x:Class="MauiApp1.MainPage">
<ScrollView>
<VerticalStackLayout
Padding="30,0"
Spacing="25">
<Label
Text="{x:Binding PageType, Source={x:Reference Self}}"
FontSize="30"
HorizontalOptions="Center" />
</VerticalStackLayout>
</ScrollView>
</ContentPage>