我想在UWP应用程序的标题栏中添加一个新的按钮,类似于这样:
我已经看到了一些“类似”的帖子,但回答并不是很清楚,缺乏细节,很难理解他们都做了什么。
默认情况下,UWP没有在标题栏中添加按钮的功能。但是UWP支持自定义标题栏布局。
要开始隐藏标题栏视图
CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;
Window.Current.SetTitleBar(UserLayout);
TitleBar
并订阅LayoutMetricsChanged
事件,用于动态创建Margin,因为系统按钮的数量不同,所以Margin也会不同。var tBar = CoreApplication.GetCurrentView().TitleBar;
tBar.LayoutMetricsChanged += OnTitleBarLayoutMetricsChanged;
添加功能
public void OnTitleBarLayoutMetricsChanged(CoreApplicationViewTitleBar sender, object args)
{
var bar = sender as CoreApplicationViewTitleBar;
RightPanel.Margin = new Thickness(0, 0, bar.SystemOverlayRightInset, 0);
}
将页面框架导航到主页
Content.Navigate(typeof(Home), null, new SuppressNavigationTransitionInfo()); // Navigate to Home page with null args and null animation
if (e.PrelaunchActivated == false) {
if (rootFrame.Content == null) {
rootFrame.Navigate(typeof(AniMiru.Windows10.Views.AppCustomWindow), e.Arguments);
}
Window.Current.Activate();
}
页面 xaml:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="32"/>
<RowDefinition />
</Grid.RowDefinitions>
<Grid x:Name="TopBar" >
<Grid x:Name="UserLayout" Background="#00000000" />
<Grid Canvas.ZIndex="1">
<StackPanel x:Name="LeftPanel" Orientation="Horizontal" VerticalAlignment="Stretch" HorizontalAlignment="Left">
<AutoSuggestBox QueryIcon="Find" PlaceholderText="Search" Width="300" />
</StackPanel>
<StackPanel x:Name="RightPanel" Orientation="Horizontal" VerticalAlignment="Stretch" HorizontalAlignment="Right">
<Button Content="" FontFamily="Segoe MDL2 Assets" FontSize="13" VerticalAlignment="Stretch" />
<Button Content="" FontFamily="Segoe MDL2 Assets" FontSize="13" VerticalAlignment="Stretch" />
</StackPanel>
</Grid>
</Grid>
<Grid Grid.Row="1">
<Frame x:Name="Content" />
</Grid>
</Grid>
页面 C#:
public AppCustomWindow()
{
this.InitializeComponent();
// Hide titlebar panel and add new layout to title bar
CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;
Window.Current.SetTitleBar(UserLayout);
// Add LayoutMetricsChanged Event to TitleBar
var tBar = CoreApplication.GetCurrentView().TitleBar;
tBar.LayoutMetricsChanged += OnTitleBarLayoutMetricsChanged;
// Navigate
Content.Navigate(typeof(Home), null, new SuppressNavigationTransitionInfo()); // Navigate to Home page with null args and null animation
}
public void OnTitleBarLayoutMetricsChanged(CoreApplicationViewTitleBar sender, object args)
{
var bar = sender as CoreApplicationViewTitleBar;
RightPanel.Margin = new Thickness(0, 0, bar.SystemOverlayRightInset, 0);
}
截图:
网址:
很抱歉我的英语不好。
最好的祝福。