Search code examples
windows-phone-7expression-blend

In Expression Blend for Windows Phone change image source of button in different states


In Expression Blend for Windows Phone, how can I change the image source of a button in different states. I want different images to be displayed in normal state and pressed state.


Solution

  • A couple of options come to mind, depending on what exactly you're trying to accomplish.

    Once scenario is that you have a button that you want to act like a toggle, where you press it once and it stays pressed until you press it again, like a play button on a tape recorder (remember those?).

    If that's what you're looking for, I would create a boolean property in your codebehind file, such as IsPlaying, that indicates whether your button is currently pressed or not.

    Then you can create a ValueConverter that translates the true and false values to different images. Here's a write-up on creating a ValueConverter. The article talks about converting a bool to a Visibility, but the concept is the same.

    In your BooleanToImage converter, or whatever you name it, you'll need to decide which image to show and load it up as a Bitmap. Then in your .xaml you'll bind to the IsPlaying property and set the converter to BooleanToImage. This approach works quite well for a lot of scenarios, and it's nice and tidy, as you don't have to think in terms of which image is playing; you can think about whether your app IsPlaying.

    The other scenario is that you want to display the image briefly when the button is pressed, like an animation, then return to the previous state. In that case, your best bet is using the VisualStateManager, which allows you to define different appearances for your button in various states, such as Normal and Clicked. You can apply animations to transition between the states. Here's a walk-through that demonstrates using the VisualStateManager.