winui3 自定义标题栏
在 MainWindow.xaml
添加
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition MinHeight="48"/>
<RowDefinition/>
</Grid.RowDefinitions>
<!-- 标题栏 -->
<Border x:Name="AppTitleBar" VerticalAlignment="Top">
<TextBlock x:Name="AppTitle" Text="{StaticResource AppTitleName}" VerticalAlignment="Top" Margin="0,8,0,0" />
</Border>
</Grid>
在 MainWindow.xaml.cs
中添加
public MainWindow()
{
this.InitializeComponent();
// 自定义标题栏
ExtendsContentIntoTitleBar = true;
SetTitleBar(AppTitleBar);
}
左侧添加按钮
如果只是在左侧添加按钮,可以直接使用 xaml 定义
在 MainWindow.xaml
添加
<Grid>
<Grid.RowDefinitions>
<RowDefinition MinHeight="48"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition MinHeight="auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Content="返回" Click="BackBtn_Click"/>
<!-- 标题栏 -->
<Border x:Name="AppTitleBar" Grid.Column="1" VerticalAlignment="Top">
<TextBlock x:Name="AppTitle" Text="{StaticResource AppTitleName}" VerticalAlignment="Top" Margin="0,8,0,0" />
</Border>
</Grid>
</Grid>
添加自定义可点击内容
如果需要在中间添加可点击可输入内容,那么就需要这样做
在 MainWindow.xaml
添加
<Grid>
<Grid.RowDefinitions>
<RowDefinition MinHeight="48"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border x:Name="AppTitleBar" VerticalAlignment="Top">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="AppTitle" Text="{StaticResource AppTitleName}" VerticalAlignment="Top" Margin="0,8,0,0" />
<TextBox x:Name="SearchTb" Grid.Column="1" />
</Grid>
</Border>
</Grid>
在 MainWindow.xaml.cs
中添加
public MainWindow()
{
this.InitializeComponent();
// 自定义标题栏
ExtendsContentIntoTitleBar = true;
SetTitleBar(AppTitleBar);
var _baseWindowHandle = WindowNative.GetWindowHandle(this);
var windowId = Win32Interop.GetWindowIdFromWindow(_baseWindowHandle);
var _appWindow = AppWindow.GetFromWindowId(windowId);
var dpiScale = Content.XamlRoot.RasterizationScale;
var nonClientSource = InputNonClientPointerSource.GetForWindowId(_appWindow.Id);
var inputPoint = SearchTb.TransformToVisual(Content).TransformPoint(new Point(0, 0));
nonClientSource.ClearRegionRects(NonClientRegionKind.Passthrough);
nonClientSource.SetRegionRects(NonClientRegionKind.Passthrough,
// 可以添加多个区域
[new(
(int)Math.Round(inputPoint.X * dpiScale),
(int)Math.Round(inputPoint.Y * dpiScale),
(int)Math.Round(SearchTb.ActualWidth * dpiScale), // 请注意,要获取到可点击元素的显示尺寸才行
(int)Math.Round(SearchTb.ActualHeight * dpiScale)
)]);
}
Command 绑定
使用 Command={TemplateBinding BackCommand}
可能无效
可以使用 Command="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=BackCommand}"
转载请保留原文链接: https://zodream.cn/blog/id/248.html