WPF--->自定义窗口,标题栏双击放大与还原&点击拖动的2种实现

本文档介绍了如何手动实现Windows应用程序窗口的标题栏功能,包括拖动窗口和双击最大化,以及如何继承并扩展微软的Title功能。通过依赖项属性绑定HeaderHeight,实现了自定义窗口的高度调整,并在XAML中设置相关属性,以在不需要标题功能的区域允许点击。此外,还展示了如何在StackPanel中添加最小化、最大化和关闭按钮。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.手动实现

Border为标题栏的边框,Border的名称为"header"

  			header = (Border)Template.FindName("header", this);
            header.MouseMove += (o, e) =>
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    this.DragMove();
                }
            };
            header.MouseLeftButtonDown += (o, e) =>
            {
                if (e.ClickCount >= 2)
                {
                    maxBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
            };

2.继承微软的Title功能

1.使用依赖项属性对header的高度进行绑定,当点击这一高度会有点击title的功能

 public int HeaderHeight
        {
            get { return (int)GetValue(HeaderHeightProperty); }
            set { SetValue(HeaderHeightProperty, value); }
        }

// Using a DependencyProperty as the backing store for HeaderHeight.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty HeaderHeightProperty =DependencyProperty.Register("HeaderHeight", typeof(int), typeof(CommonWindow), new PropertyMetadata(0));

public CustomWindow
{
	BindingOperations.SetBinding(chrome, WindowChrome.CaptionHeightProperty,new Binding(nameof(HeaderHeight)) { Source = this });
}

  1. 在xaml中进行依赖属性的绑定,并且在不需要title功能的地方加上WindowChrome.IsHitTestVisibleInChrome="True"
<Border Name="header" Background="{DynamicResource WindowTitleBrush}" BorderThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BorderThickness}">
	<StackPanel WindowChrome.IsHitTestVisibleInChrome="True" DockPanel.Dock="Right"  HorizontalAlignment="Right" VerticalAlignment="Top" Orientation="Horizontal" Height="Auto" >
             <Button x:Name="btnMin"/>
             <Button x:Name="btnMax"/>
             <Button x:Name="btnClose"/>
    </StackPanel>
</Boder>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值