XAML 在.NET MAUI应用程序中未指定背景颜色的边框不透明度

dhxwm5r4  于 2023-01-03  发布在  .NET
关注(0)|答案(1)|浏览(230)

我有一个简单的,无主题的毛伊岛应用程序。毛伊岛的默认颜色绑定工作,当我改变Windows主题之间的黑暗和光明,这是我想要的。
我有一个Border对象,它是Grid布局的一部分,并且位于其他元素之上。出于视觉设计的原因,我希望其他元素通过它部分可见,所以我将其Opacity设置为0.75。我没有指定其背景色,因为我希望它使用当前系统主题的默认值。直到最近,这种方法才奏效。但现在似乎只有在显式指定背景颜色时才应用不透明性-由于上述原因,我不想这样做。是否有办法在不硬编码背景颜色的情况下获得部分不透明的Border
下面的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:Class="MauiApp1.MainPage">
    <Grid>
        <VerticalStackLayout
            Grid.Row="0" Grid.Column="0">
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
        </VerticalStackLayout>
        <Border
            Opacity="0.75"
            Grid.Row="0" Grid.Column="0" ZIndex="99"
            HorizontalOptions="Start" VerticalOptions="Start"
            WidthRequest="200"  HeightRequest="100"
            Stroke="white" StrokeThickness="3"/>
    </Grid>
</ContentPage>

运行这个函数得到以下结果,其中Label元素没有被Border不透明化:

例如,如果我将Border元素的xaml更改为包含BackgroundColor="LightGreen",则会得到以下结果,其中Label元素 * 被Border * 不透明:

我 * 确实 * 想要不透明,但我 * 不 * 想要硬编码背景颜色-我希望Maui根据系统主题选择合适的颜色。**我如何实现这一点?**我是否必须为应用设置主题并严格指定元素颜色?
(我的目标Windows和Mac只使用.net 6在当前的VS 2022主线上的Win 11。

hivapdat

hivapdat1#

由于您需要一个可以应用不透明度的背景颜色,因此需要设置一个,否则您将为透明背景设置不透明度,这是毫无意义的。
为了实现使用Border覆盖某些内容的目标,您可以将Border的背景设置为与页面背景相同的颜色。由于您只使用亮和暗,假设这是使用AppThemeBinding设置的,您可以执行以下操作:

<?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:Class="MauiApp1.MainPage">
    <Grid>
        <VerticalStackLayout
            Grid.Row="0" Grid.Column="0">
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
            <Label Text="Hello world!"/>
        </VerticalStackLayout>
        <Border
            BackgroundColor="{AppThemeBinding Light={StaticResource White}, Dark={StaticResource Black}}"
            Opacity="0.75"
            Grid.Row="0" Grid.Column="0" ZIndex="99"
            HorizontalOptions="Start" VerticalOptions="Start"
            WidthRequest="200"  HeightRequest="100"
            Stroke="white" StrokeThickness="3"/>
    </Grid>
</ContentPage>

本质上,您的边框只需要能够响应应用主题的更改。您可以在官方文档中找到有关如何响应的详细信息:https://learn.microsoft.com/en-us/dotnet/maui/user-interface/system-theme-changes?view=net-maui-7.0

相关问题