XAML 如何在MAUI中根据主题设置属性的默认值

b4lqfgs4  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(136)

我有一个简单的组件在MAUI.下面是简化的代码.
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>

我想根据当前的应用程序主题设置此属性的默认值,所以当我使用它像

<components:LabeledValue ValueColor="{StaticResource Blue}"/>

它是蓝色的,但当我简单地做

<components:LabeledValue />

颜色是根据主题设置的。我该怎么做?

8cdiaqws

8cdiaqws1#

您可以使用AppThemeBinding和提供的扩展来实现。
首先,您需要删除到TextColor的绑定,因为这需要从代码隐藏中设置,并且还给予使用x:Name属性为Label命名:

<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>

然后,在代码隐藏中,您需要在构造函数中以编程方式设置AppThemeBinding

public LabeledValue()
{
    InitializeComponent();
    
    //set default values for AppThemeBinding
    MyLabel.SetAppThemeColor(Label.TextColorProperty, Colors.Blue, Colors.White);
}

最后,您需要添加一个属性更改处理程序,用于在用户覆盖默认设置时设置TextColor

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;
    }
}

当你使用LabeledValue控件时,你可以使用默认的行为,它将响应应用主题或覆盖它:

<!-- use default AppThemeBinding values -->
<components:LabeledValue/> 

<!-- permanently set the ValueColor to Orange-->
<components:LabeledValue ValueColor="Orange"/>

您可以在我的MAUI Samples存储库中找到一个工作示例。

相关问题