背景: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屬性來判斷雙擊。
