As you've noticed, the iPhone switches off WiFi when it sleeps and uses 3G. This is by design. The 3G radio consumes less battery power.
When does the iPhone switch back to 3G even if it has WiFi signal?
As soon as you wake the phone it will being re-enabling sleep-disabled services like the WiFi radio. If you were previously joined to a wireless network that is still within range your phone should re-join that network a few seconds after you wake it up. Here is where problems can crop up - a burp in your router or temporary interference can prevent the WiFi from rejoining and if your data coverage is fast enough, you may not notice you are now on paid 3G data. Especially if you are streaming video or playing a game and the menu bar is hidden.
If will switch back to 3G if you tell it to forget the current Wi-Fi network it's joined to and have it set to no auto-join any other known network in range. Or shortly after you put it back to sleep.
Can I modify this behavior somewhere?
All of the Wi-Fi behaviour is set using the Settings app, under the Wi-Fi menu.
You can turn the Wi-Fi radio off completely here. This will stop the phone from searching for wireless networks altogether and you'll be running completely on cellular data services. (See #1 in screen shot)
You can set what the phone does if the Wi-Fi radio is on, networks are detected, but it is not currently joined to any of them. In this circumstance the phone can prompt you to join a network or do nothing and let you manually join a network if you so desire. (See #2 in the screen shot).
You can also manually chose a network here. And, if you're currently joined to a network, you can click the > arrow next to its name to get the details and, if you want to, "forget" the network and disconnect from it.