WPF中自定义窗体标题栏

 

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

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

view plain copy to clipboard print ?
  1. private void TitleBar_MouseMove(object sender, MouseEventArgs e)  
  2.         {  
  3.             if (e.LeftButton == MouseButtonState.Pressed)  
  4.             {  
  5.                 this.DragMove();  
  6.             }  
  7.         }  
private void TitleBar_MouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { this.DragMove(); } }
如果没有为自定义的TitleBar添加MouseMove事件,那么就无法拖动窗体。

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

前台所有代码:

view plain copy to clipboard print ?
  1. <Window x:Class="WpfStudy.Window1"  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" WindowStyle="None"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  WindowStartupLocation="CenterScreen" Topmost="False"  
  4.     SizeToContent="WidthAndHeight"     >      
  5.     <Grid >         
  6.         <Grid.RowDefinitions>  
  7.             <RowDefinition Height="Auto"/>  
  8.             <RowDefinition Height="150"/>  
  9.         </Grid.RowDefinitions>  
  10.         <Grid.ColumnDefinitions>  
  11.             <ColumnDefinition Width="300"/>             
  12.         </Grid.ColumnDefinitions>  
  13.         <Grid Grid.Row=" 0" x:Name="TitleBar" Height="Auto" MouseMove="TitleBar_MouseMove" Background="Bisque">  
  14.             <TextBlock Text="这是标题栏" FontSize="15" />  
  15.         </Grid>  
  16.         <Grid Grid.Row=" 1" Background="Azure"></Grid>          
  17.     </Grid>  
  18. </Window>  
<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>
效果图:

WPF中自定义窗体标题栏_第1张图片

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

你可能感兴趣的:(object,Class,WPF)