在WPF中自定义窗体标题栏,首先需要将窗体的WindowStyle属性设置为None,隐藏掉WPF窗体的自带标题栏。然后可以在窗体内部自定义一个标题栏。
例如,标题栏如下:
<WrapPanel Height="30" MouseMove="TitleBar_MouseMove" MouseDown="TitleBar_MouseDown" Background="#4C9CFB" DockPanel.Dock="Top"> <TextBlock Name="txtTitle" Margin="1,0,0,0" Padding="5,3,2,3" Text="个人信息" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="14" FontFamily="微软雅黑" Foreground="White"/> <custom:ImageButton x:Name="btn_min" Template="{StaticResource ImageButton_Template}" Margin="560,5,0,0" Source="../res/img/btn_min1.jpg" ImgWidth="14" ImgHeight="14" Click="btn_min_Click" Grid.Column="0"/> <custom:ImageButton x:Name="btn_max" Template="{StaticResource ImageButton_Template}" Margin="30,5,0,0" Source="../res/img/btn_close1.jpg" ImgWidth="14" ImgHeight="14" Click="btn_close_Click"> </custom:ImageButton> </WrapPanel>
在后台,为TitleBar添加了MouseMove事件,后台处理代码:
#region 标题栏事件 /// <summary> /// 窗口移动事件 /// </summary> private void TitleBar_MouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { this.DragMove(); } }
int i = 0; /// <summary> /// 标题栏双击事件 /// </summary>
private void TitleBar_MouseDown(object sender, MouseButtonEventArgs e) { i += 1; System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer(); timer.Interval = new TimeSpan(0, 0, 0, 0, 300); timer.Tick += (s, e1) => { timer.IsEnabled = false; i = 0; }; timer.IsEnabled = true;
if (i % 2 == 0) { timer.IsEnabled = false; i = 0; this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized; } }
/// <summary> /// 窗口最小化 /// </summary> private void btn_min_Click(object sender, RoutedEventArgs e) { this.WindowState = WindowState.Minimized; //设置窗口最小化 } /// <summary> /// 窗口最大化与还原 /// </summary> private void btn_max_Click(object sender, RoutedEventArgs e) { if (this.WindowState == WindowState.Maximized) { this.WindowState = WindowState.Normal; //设置窗口还原 } else { this.WindowState = WindowState.Maximized; //设置窗口最大化 } } /// <summary> /// 窗口关闭 /// </summary>
private void btn_close_Click(object sender, RoutedEventArgs e) { this.Close(); } #endregion 标题栏事件