背景:WPF窗体需要实现双击窗体最上方的标题条实现最大化和还原
1.通过命令绑定的方式实现
xaml代码
1 <Grid x:Name="leftTop" Grid.Row="0" Grid.Column="0" Background="{StaticResource DarkBG}"> 2 <Grid.InputBindings> 3 <MouseBinding MouseAction="LeftDoubleClick" Command="{Binding DoubleClickMaximizeWindowCommand,RelativeSource={RelativeSource TemplatedParent}}"></MouseBinding> 4 </Grid.InputBindings> 5 </Grid>
绑定部分代码:
public ICommand DoubleClickMaximizeWindowCommand { get; protected set; } var bind4 = new CommandBinding(DoubleClickMaximizeWindowCommand); bind4.Executed += DoubleClickMaxCommand_Execute; this.CommandBindings.Add(bind4); private void DoubleClickMaxCommand_Execute(object sender, ExecutedRoutedEventArgs e) { this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized; e.Handled = true; }
2.如果不使用绑定的实现
xaml代码
1 <Grid x:Name="leftTop" Grid.Row="0" MouseDown="LeftTop_MouseDown" 2 </Grid>
对应的.xaml.cs代码
1 private void LeftTop_MouseDown(object sender, MouseButtonEventArgs e) 2 { 3 if (e.ClickCount == 2) 4 { 5 this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized; 6 e.Handled = true; 7 } 8 }
备注:
因为Grid并没有暴露出直接能用的DoubleClick事件(所以事件绑定时使用Grid.InputBindings),所以通过MouseDown的参数MouseButtonEventArgs中的ClickCount属性来判断双击。