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

原文出处:https://www.cnblogs.com/zhuiyishanran/p/11648372.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章