WPF中自定义窗体标题栏

来源:互联网 发布:西门子博途软件 编辑:程序博客网 时间:2024/05/21 16:18

在WPF中自定义窗体标题栏,首先需要将窗体的WindowStyle属性设置为None,隐藏掉WPF窗体的自带标题栏。然后我们可以在窗体内部自定义一个标题栏,比如标题栏如下:

<Grid Grid.Row=" 0" x:Name="TitleBar" MouseMove="TitleBar_MouseMove" >            <TextBlock Text="这是标题栏" FontSize="15" /></Grid>
注意,我们给TitleBar添加了MouseMove事件,后台处理代码:

private void TitleBar_MouseMove(object sender, MouseEventArgs e)        {            if (e.LeftButton == MouseButtonState.Pressed)            {                this.DragMove();            }        }

如果没有为自定义的TitleBar添加MouseMove事件,那么就无法拖动窗体。

当然我写的这个标题栏比较简单,只是为了演示,大家可以扩充,根据需求放置最大化、最小化、关闭按钮等。

前台所有代码:

<Window x:Class="WpfStudy.Window1"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" WindowStyle="None"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  WindowStartupLocation="CenterScreen" Topmost="False"    SizeToContent="WidthAndHeight"     >        <Grid >               <Grid.RowDefinitions>            <RowDefinition Height="Auto"/>            <RowDefinition Height="150"/>        </Grid.RowDefinitions>        <Grid.ColumnDefinitions>            <ColumnDefinition Width="300"/>                   </Grid.ColumnDefinitions>        <Grid Grid.Row=" 0" x:Name="TitleBar" Height="Auto" MouseMove="TitleBar_MouseMove" Background="Bisque">            <TextBlock Text="这是标题栏" FontSize="15" />        </Grid>        <Grid Grid.Row=" 1" Background="Azure"></Grid>            </Grid></Window>

效果图:


这个示例够简单了,实在是不能再简化了~~