Pages

Saturday, March 3, 2012

WP7 Code snippets

A few useful Windows Phone 7 code snippets.


Check if there is a network connection available.

bool isAvailable = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

Detect when the the shell chrome is covering the frame with the Obscured Event. E.g. incoming call

//Register for the Obscured event
PhoneApplicationFrame rootFrame = ((App)Application.Current).RootFrame;
rootFrame.Obscured += new EventHandler<ObscuredEventArgs>(rootFrame_Obscured);

//Handle the event
void rootFrame_Obscured(object sender, ObscuredEventArgs e)
{
    // ...
}

When doing any form of Trig you will need to be working in Radians rather than degrees.

Math.Sin(Microsoft.Xna.Framework.MathHelper.ToRadians((float)degrees));

URL-encode portions of a URI such as query strings and path components (alternative to HttpUtility.UrlEncode)


Check if the code is running in the designer. Useful to avoid code that would fail if the application isn't actually running.

if (DesignerProperties.GetIsInDesignMode(Application.Current.RootVisual))
{
    return;
}

Declare a Primary Key via System.Data.Linq.Mapping for a SQL CE database where the value will be kept in sync with the database after insert.

[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL IDENTITY", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int Id { get; set; }

Enumerate the values in a Enum. Note that Enum.GetValues() not available in the Windows Phone 7 API.

Type enumType = typeof(MyEnum);
foreach (var x in enumType.GetFields()) {
   if (x.IsLiteral) {
    MyEnum enumValue = (MyEnum)x.GetValue(enumType);
   }
}

Navigate to another page from a User Control. Stack Overflow - Silverlight - How to navigate from a User Control to a normal page?

(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(uri);

No comments:

Post a Comment