Fork me on GitHub

UWP-TitleBar

Week 2

标题栏透明化

MyList

看着自己做好的 MyList,总觉得和正常的 application 差了点什么。这个可恶的标题栏,为什么不是透明的啊,这突然突出来的白色,真是让人不开心。那么,接下来就了解一下标题栏的透明化。

在 MS 的 Docs 搜索之后,可以找到 CoreApplicationViewTitleBar 类。是的,这个就是我们想要的标题栏。文档很短,不过,它提供了我们需要的透明化功能(伪透明)。
CoreApplicationViewTitleBar 有 ExtendViewIntoTitleBar 方法,官档叙述如下:

ExtendViewIntoTitleBar:

Gets or sets a value that specifies whether this title bar should replace the default window title bar.
Set to true to replace the default window title bar; otherwise, false.

Remarks

The first time the app runs, and for secondary views, the default value is false. For the main view of an app, this value persists between application runs.

这个方法可以将应用界面拓展到标题栏。所以,我们需要的透明化,可以从这里下手。为了让所有页面的标题栏都同样透明化,我们应该在哪里修改代码呢?看过前面博客的同学应该还有印象。是的,在 app.xaml.cs 文件中。这个文件中定义的方法可以应用于所有 page 。

我们需要添加的代码,就一行:

1
CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;

之后,我们的 UI 就变成这样啦!

MyList

不过,还有个问题,右上角的命令三连按钮。他们的颜色,绝对是不可忍受的!那么,还要继续修改。但是 CoreApplicationViewTitleBar 并没有关于这三个按钮的信息。于是继续查阅资料。果然,还是可以动手的。我们还有一个 ApplicationViewTitleBar 类(是的,还有这个类)。官档中给出了这个类的很多方法,其中基本都是修改 titleBar 的颜色样式的。那么,自然我们可以写出这样的代码:

1
ApplicationView.GetForCurrentView().TitleBar.ButtonBackgroundColor = Colors.White;

运行结果,并不是我们要的那样,只是背景颜色变白了。那么,我们怎么把它们的背景变透明呢?针对这个属性,查看官档:

ButtonBackgroundColor

Gets or sets the background color of the title bar buttons.

Value
Nullable < Color>

他的值是 Color,那么我们去看看官档中对于 Color 的描述。经过仔细查找,我们发现这么两句话:

  1. Color is a Windows Runtime structure that represents a color that has four channels: A (alpha), R (red), G (green), B (blue).
  2. Color has a static method FromArgb that acts as a Color value generator

它是一个struct,值域有 A (alpha), R (red), G (green), B (blue)。其中 A(alpha) 可以制造出我们需要的透明效果!那么,更新代码如下:

1
ApplicationView.GetForCurrentView().TitleBar.ButtonBackgroundColor = Color.FromArgb(0, 0, 0, 0);

这么一来,好看的标题栏,就做出来了!

MyList

总结一下,官方文档还是很有用的。