如何创建引用多个控件的 WPF 行为?

发布于 2024-11-03 19:17:46 字数 235 浏览 1 评论 0原文

我有一个包含大图像的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

oО清风挽发oО 2024-11-10 19:17:46

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.

ゞ花落谁相伴 2024-11-10 19:17:46

您无需附加到元素即可向其添加事件处理程序。如果您的 AssociatedObjectScrollViewer 那么您可能能够像这样获得对图像的引用:

var image = AssociatedObject.Content as Image;

然后您可以添加一个鼠标事件处理程序:

image.MouseLeftButtonDown += (s, e) => Debug.WriteLine("Clicked!");

所以您的对象所附加的关联对象是您的“大本营”,但您可以使用任何您可以接触到的对象,包括使用 VisualTreeHelper 来遍历可视化树。

You don't need to attach to an element to be able to add an event handler to it. If your AssociatedObject is a ScrollViewer then you might be able to get a reference to the image like this:

var image = AssociatedObject.Content as Image;

and then you can add a mouse event handler:

image.MouseLeftButtonDown += (s, e) => Debug.WriteLine("Clicked!");

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文