鼠标绑定鼠标滚轮以放大 WPF 和 MVVM [英] MouseBinding the mousewheel to zoom in WPF and MVVM

查看:29
本文介绍了鼠标绑定鼠标滚轮以放大 WPF 和 MVVM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我已经知道如何通过使用 LayoutTransform 和 ScaleTransform 来缩放 UI 元素网格.我不明白的是如何让我的视图响应 CTRL+MouseWheelUp\Down 来执行它,以及如何使代码适合 MVVM 模式.

OK, I've figured out how to get my Grid of UI elements to zoom, by using LayoutTransform and ScaleTransform. What I don't understand is how I can get my View to respond to CTRL+MouseWheelUp\Down to do it, and how to fit the code into the MVVM pattern.

我的第一个想法是将 ZoomFactor 存储为一个属性,并绑定到一个命令来调整它.

My first idea was to store the ZoomFactor as a property, and bind to a command to adjust it.

我在看类似的东西:

<UserControl.InputBindings>
 <MouseBinding Command="{Binding ZoomGrid}" Gesture="Control+WheelClick"/>
</UserControl.InputBindings>

但我看到了两个问题:

1) 我认为没有办法判断轮子是向上还是向下移动,也看不出如何确定.我见过 MouseWheelEventArgs.Delta,但不知道如何获得它.

1) I don't think there is a way to tell whether the wheel was moved up or down, nor can I see how to determine by how much. I've seen MouseWheelEventArgs.Delta, but have no idea how to get it.

2) 绑定到视图模型上的命令似乎不正确,因为它严格来说是视图的事情.

2) Binding to a command on the viewmodel doesn't seem right, as it's strictly a View thing.

由于缩放只是严格的 UI 视图,我认为实际代码应该放在代码隐藏中.

Since the zoom is strictly UI View only, I'm thinking that the actual code should go in the code-behind.

你们将如何实现这一点?

How would you guys implement this?

ps,我正在使用 .net\wpf 4.0,将 Cinch 用于 MVVM.

p.s., I'm using .net\wpf 4.0 using Cinch for MVVM.

推荐答案

我建议您在 VM 中实现通用缩放命令.该命令可以使用新的缩放级别进行参数化,或者(也许更简单)您可以实现 IncreaseZoomCommandDecreaseZoomCommand.然后在处理完鼠标滚轮事件的事件参数后,使用视图的代码来调用这些命令.如果 delta 为正,则放大,如果为负,则缩小.

I would suggest that you implement a generic zoom command in your VM. The command can be parameterized with a new zoom level, or (perhaps even simpler) you could implement an IncreaseZoomCommand and DecreaseZoomCommand. Then use the view's code behind to call these commands after you have processed the event arguments of the Mouse Wheel event. If the delta is positive, zoom in, if negative zoom out.

后面用几行代码解决这个问题没有什么坏处.MVVM 的主要思想是,您可以在不依赖于 UI(增强可测试性)的对象中跟踪和修改视图的几乎完整状态.因此,作为缩放结果的新视口的计算应该在 VM 中完成,而不是在后面的代码中完成.

There is no harm in solving this problem by using a few lines of code behind. The main idea of MVVM is that, you are able to track and modify nearly the complete state of your view in an object that does not depend on the UI (enhances the testability). In consequence, the calculation of the new viewport which is the result of the zoom should be done in the VM and not in code behind.

背后代码中存在的可测试性的小差距可以被自动 UI 测试忽略或覆盖.然而,自动 UI 测试可能非常昂贵.

The small gap of testability that exists in the code behind can either be disregarded or covered by automatic UI tests. Automatic UI tests, however, can be very expensive.

这篇关于鼠标绑定鼠标滚轮以放大 WPF 和 MVVM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆