开发者

How can I create a WPF behavior that refers to multiple controls?

I have a ScrollViewer that contains a large image.开发者_如何学Go 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜