I have a simple component in MAUI. Below is simplified code.
C#:
public partial class LabeledValue : ContentView
{
public static readonly BindableProperty ValueColorProperty = BindableProperty.Create(
nameof(ValueColor), typeof(Color), typeof(LabeledValue), default(Color), BindingMode.OneWay);
public Color ValueColor
{
get { return (Color)GetValue(ValueColorProperty); }
set { SetValue(ValueColorProperty, value); }
}
}
XAML:
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="EpexMauiApp.Components.LabeledValue"
x:Name="self">
<Label Text="Dummy text" FontAttributes="Bold" TextColor="{Binding ValueColor, Source={x:Reference self}}"/>
</ContentView>
I would like to set default value of this property based on current app theme, so when I use it like
<components:LabeledValue ValueColor="{StaticResource Blue}"/>
It's blue but when I simply do
<components:LabeledValue />
Color is set based on theme. How can I do that?
You can use AppThemeBinding and the provided Extensions for that.
First, you need to remove the binding to TextColor
, because this will need to be set from the code-behind, and also give the Label
a name using the x:Name
attribute:
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="EpexMauiApp.Components.LabeledValue"
x:Name="self">
<Label x:Name="MyLabel" Text="Dummy text" FontAttributes="Bold"/>
</ContentView>
Then, in your code-behind, you need to set the AppThemeBinding
programmatically in the constructor:
public LabeledValue()
{
InitializeComponent();
//set default values for AppThemeBinding
MyLabel.SetAppThemeColor(Label.TextColorProperty, Colors.Blue, Colors.White);
}
Finally, you need to add a property changed handler that sets the TextColor
when the user overrides the default setting:
public partial class LabeledValue : ContentView
{
public Color ValueColor
{
get { return (Color)GetValue(ValueColorProperty); }
set { SetValue(ValueColorProperty, value); }
}
public static readonly BindableProperty ValueColorProperty = BindableProperty.Create(nameof(ValueColor), typeof(Color), typeof(LabeledValue), propertyChanged: OnValueColorPropertyChanged);
private static void OnValueColorPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
((LabeledValue)bindable).MyLabel.TextColor = (Color)newValue;
}
}
When you use the LabeledValue
control, you can either use the default behavior, which will respond to the App Theme or override it:
<!-- use default AppThemeBinding values -->
<components:LabeledValue/>
<!-- permanently set the ValueColor to Orange-->
<components:LabeledValue ValueColor="Orange"/>
You can find a working example for this in my MAUI Samples repository.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments