Category Archives: Code Tips

Setting a Windows Phone Button Background in C#

There might be a case where you need to set the background color of a button in code rather than in XAML. Or you might define a style in XAML with a particular button background color, but would like to change the background color in an event handler. For example, let’s say you created the following button in XAML:

<Button Content=”My Button”
Background=”{StaticResource PhoneAccentBrush}”
Click=”RegisterSelection_Click”/>

Now let’s say that when the user clicks the button you want to change the button’s background color to give another way of indicating the button has been selected. You can do the following in C#:

private void RegisterSelection_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
btn.Background = App.Current.Resources[“PhoneChromeBrush”] as SolidColorBrush;
}

I am using this in an app I am currently working on and it works well. Give it a try.

Overriding the Default Windows Phone Back Button Action

Here is a great blog post showing how to override the default action of the back button.

This can be very handy when interacting with pop-ups and dialogs within your app. For example, you may have a pop-up menu that you want the user to be able to back out of using the back button. Depending on your app’s design, the standard back button action might go so far as to exit the app. By overriding the standard action, the user could close the dialog instead.

Code samples are included in the post.