如何创建引用多个控件的 WPF 行为?
我有一个包含大图像的 ScrollViewer。我希望用户能够按住鼠标并拖动图像以将其从一边移动到另一边,我正在尝试使用行为来实现这一点。问题是,当用户按下鼠标按钮时,鼠标按下事件似乎无法在 ScrollViewer 上触发。通过后面的代码,我将处理图像上的该事件,但由于仅附加到一个控件的行为,我不知道如何解决此问题。
我应该使用什么方法来创建附加到两个对象的 System.Windows.Interactivity.Behavior?
I have a ScrollViewer that contains a large image. I want the user to be able to hold the mouse down and drag the image to move it side to side, and I'm trying to implement this using a Behavior. The problem is that the mouse down event doesn't seem to be able to fire on the ScrollViewer when a user presses down on the mouse button. With a code behind, I would handle that event on the image, but with a behavior that is only attached to one control I don't know how to approach this issue.
What approach should I use to create a System.Windows.Interactivity.Behavior that attaches to both objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MouseLeftButtonDown 事件在 ScrollViewer 上正常引发。问题是 ScrollViewer 正在处理事件本身(e.Handled = true)。由于它已经被处理,你的行为不会收到它。
根据您正在执行的操作,您可能可以只使用 PreviewMouseLeftButtonDown 事件。这样,ScrollViewer 是否会处理它并不重要,因为Behavior 首先接收它。
您还可以尝试直接使用拖放事件。但我不确定这是否有效。
The MouseLeftButtonDown event is raised just fine on the ScrollViewer. The problem is that the ScrollViewer is handling the event itself (e.Handled = true). And since it is already handled your behavior do not receive it.
Depending on what you are doing you might be able to just use the PreviewMouseLeftButtonDown event instead. This way it doesn't matter if the ScrollViewer will handle it since the Behavior is receiving it first.
You could also try to use the Drag&Drop events directly. But I'm not sure if that will work.
您无需附加到元素即可向其添加事件处理程序。如果您的
AssociatedObject
是ScrollViewer
那么您可能能够像这样获得对图像的引用:然后您可以添加一个鼠标事件处理程序:
所以您的对象所附加的关联对象是您的“大本营”,但您可以使用任何您可以接触到的对象,包括使用 VisualTreeHelper 来遍历可视化树。
You don't need to attach to an element to be able to add an event handler to it. If your
AssociatedObject
is aScrollViewer
then you might be able to get a reference to the image like this:and then you can add a mouse event handler:
So the object you are attached to, your associated object, is your "home base", but you can work with any object you can get your hands on up to and including using
VisualTreeHelper
to walk the visual tree.