天天看点

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

文章目录

    • 1.手动实现
    • 2.继承微软的Title功能

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>
           

继续阅读