欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-07 14:25:54
...

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>