Dragging elements around in Silverlight is not trivial, so I wrote a Drag class in IronRuby during a demo of DLRConsole to show how cool REPL-programming is. I did a 10-minute screencast of this same demo a while ago, but I've given this demo enough times that it deserves a post on its own.
Can't show dragging without having stuff to drag, can I? Well, rather than requiring you to download a bunch of stuff, let's just program in the browser. Yes, the browser.
You'll need Silverlight 2 Beta 2, but DLRConsole will tell you to install Silverlight if you don't have it.
If you haven't been introduced to DLRConsole yet, there she is. Pretty straight-forward; a Ruby and Python REPL prompt on the left for typing code in, and a Silverlight canvas on the right for pretty stuff to come out. Got it? Good.
Makin' some stuff to drag
So what do you want to drag around? I know, a clock? Of course, since we can't get enough of those freakin' things in Silverlight-land. I've done you a favor and build a clock already, so you don't have to. You're welcome. Click on the "Ruby" text on the bottom left to switch the console to Ruby, and then type the following in the prompt:
require 'lib/clock' $clock = Clock.show
Awesome, a clock, in all it's majesty. You might have the urge to try to click said clock to move it ... go ahead, it won't bite.
Drag that face all over the place
Didn't move, huh? Sucks. Let's fix that. Go back to the console and type this:
require 'lib/drag' Drag.new($clock.canvas)
And for the curious, here's the code in lib/drag.rb:
class Drag def initialize(obj) @click = nil @obj = obj end def enable @obj.mouse_left_button_down do |s,e| @click = e.get_position @obj end Application.current.root_visual.mouse_left_button_up do |s,e| @click = nil end canvas.mouse_move do |s,e| unless @click.nil? mouse_pos = e.get_position canvas @obj.left, @obj.top = mouse_pos.x - @click.x, mouse_pos.y - @click.y end end self end end
Now click, hold, and moooooove! Awesome, we can move shit. Go ahead, get carried away. Try to find that "Silverlight Canvas" TextBlock and make that dragg-able too. Enjoy your new found powers.