WPF窗体 Grid的双击事件绑定Command


背景: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属性来判断双击。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM