Posts Tagged ‘.Net’

.Net, Windows Phone 7 WP7 – Using IsolatedStorageSettings

0 Comments

In a previous tutorial, I wrote about using the Isolated Storage to store files on a WP7 device. Let’s say that instead of storing data, you wanted to store settings for your application. This where the IsolatedStorageSettings comes in.

The IsolatedStorageSettings is a place to store Key/Value pairs of data.

So let’s say that my application used the Microsoft Ad control, but I wanted to be nice and give the user the ability to turn the ads on and off.

On my Settings screen, I would have a checkbox(AdsCheckbox) for allowing the ads. In code, I would save the value by doing this…

var settings = IsolatedStorageSettings.ApplicationSettings;

if (settings.Contains("AllowAds"))
    settings["AllowAds"] = AdsCheckbox.IsChecked.Value;
else
    settings.Add("AllowAds", AdsCheckbox.IsChecked.Value);

settings.Save();

If you will notice, the ApplicationSettings object does have a method that allows you to check to see if the key already exists in the Settings. An exception will be thrown if you try to add a key that already exists, so it’s necessary to do this check before assigning a value.

Also, as you can see, it’s very easy to get the value out of the settings…

// when the form opens, I want to set the Checkbox to being checked
//   or unchecked depending on the setting
var settings = IsolatedStorageSettings.ApplicationSettings;

if (settings.Contains("AllowAds"))
    AdsCheckbox.IsChecked = bool.Parse(settings["AllowAds"].ToString());

However, the IsolatedStorageSettings class isn’t only for simply datatypes. It can also store your custom class objects.

Employee class

public class Employee
{
    public string FullName { get; set; }
    public decimal Salary { get; set; }
}

Then on my form, I have a button to save an instance of the Employee class to the IsolatedStorageSettings

private void btnSave_Click(object sender, RoutedEventArgs e)
{
    var settings = IsolatedStorageSettings.ApplicationSettings;

    Employee emp = new Employee()
    {
        FullName = "John Doe",
        Salary = 250000
    };

    settings.Add("Employee1", emp);
    settings.Save();
}

I also have a button that will load the object from the IsolatedStorageSettings

private void btnLoad_Click(object sender, RoutedEventArgs e)
{
    var settings = IsolatedStorageSettings.ApplicationSettings;

    Employee emp;

    if (settings.TryGetValue<Employee>("Employee1", out emp))
    {
         MessageBox.Show(string.Format("Full Name: {0}\nSalary: {1:c}", emp.FullName, emp.Salary));
    }
}

Notice that the IsolatedStorageSettings.ApplicationSettings class also has the TryGetValue method. This method behaves exactly like the TryParse methods of the .Net datatypes. It will return a boolean specifying whether the key was found and whether the conversion from object –> Employee was successful. If it’s successful, it will return the instance as the out parameter.

After running the application, clicking the Save button, then clicking the Load button, we will get this message box…

2

Tags: , , , , ,

.Net C# – Get Windows Mobile Theme Color

1 Comment

I recently had a business requirement to color the background of a TextBox in Windows Mobile to a specific color.  After completing the tasks, I noticed that the color that was chosen(blue) didn’t look right on devices that used a different theme like red or green.  So I decided to figure out how to set the background color to match the theme color.

The theme system colors are located in the registry entry HKLM\System\GWE\SysColor.  This registry entry is a BLOB that contains 29 DWORD values that correspond to the different colors of the theme.

For my application, I decided to use the color of the title bar of active windows.  This color is normally the dominate color of the theme.  This color is the third DWORD value in the registry entry.

Each DWORD value in the registry entry is a 4 byte HEX value that corresponds to a specific color.  The first byte is the RED value, second value is the GREEN value, third value is the BLUE value, and the fourth value is always 0.

For this code, I used the OpenNetCF framework to get the registry values.

/// <summary>
/// Gets the theme color
/// </summary>
/// <returns> Returns a Color or null</returns>
public Color? GetThemeColor()
{
    try
    {
         // gets the registry key
         RegistryKey keyColor = Registry.LocalMachine.OpenSubKey(@"System\GWE");

         // keyColor will be null if registry key was not found
         if (keyColor == null)
             return null;

        byte[] data = (byte[])keyColor.GetValue("SysColor");

        if (data[8] != 0 && data[9] != 0 && data[10] != 0)
        {
             // the third set of values is for the color of the
             //    title bar of an active window.
             int red = Convert.ToInt32(data[8]);
             int green = Convert.ToInt32(data[9]);
             int blue = Convert.ToInt32(data[10]);

             return Color.FromArgb(red, green, blue);
        }

        return null;
    }
    catch
    {
         return null;
    }
}

Usage is pretty simple for the method…

Color? themeColor = GetThemeColor();

if(themeColor != null)
   txtComments.BackColor = themeColor;
Tags: , ,

.Net WPF – Using Data Triggers

3 Comments

Data triggers are a great feature of WPF. They allow you to change the style properties of a control depending on the data of the bound items of that control.

In this tutorial, I am going to bind a set of data to a ListBox, and use Data Triggers to let me know when something is wrong.

So first, I am going to create a Person class. This class will have three public properties: Name, Age, and IsValid. All three properties will be readonly. The IsValid property will return whether the data of the class is good or not.

Person.cs

public class Person
{
    private string name;

    public string Name
    {
        get { return name; }
        private set { name = value; }
    }
    private int age;

    public int Age
    {
        get { return age; }
        private set { age = value; }
    }

    public bool IsValid
    {
        // will return false if either the name is blank
        //   or if the age is 0.
        get { return (!string.IsNullOrEmpty(name) && age != 0); }
    }

    public Person(string _name, int _age)
    {
        name = _name;
        age = _age;
    }
}

This is a simple example to show the concept. Basically, I am going to set the data to values that we don’t want.


MainWindow.xaml.cs

public partial class MainWindow : Window
{
    ObservableCollection<Person> col;

    public MainWindow()
    {
        InitializeComponent();

        this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        col = new ObservableCollection<Person>();
        col.Add(new Person("John Doe", 24));
        col.Add(new Person("", 24));
        col.Add(new Person("John Doe", 0));

        PersonListBox.ItemsSource = col;
    }
}

As you can see, I set the name to being blank for one object, and the age to being 0 for another object.

Now for the XAML. First, we need to add a new style to the Window.Resources. This style will target the ListBoxItem type.

<Window.Resources>
    <Style TargetType="{x:Type ListBoxItem}" x:Key="ItemStyle">
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsValid}" Value="false">
                <Setter Property="Background" Value="Red" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

So if our IsValid property is false, then we will set the Background property of the ListBoxItem to Red.

Then we have our ListBox,

<Grid>
   <ListBox
       Name="PersonListBox"
       ItemsSource="{Binding}"
       ItemContainerStyle="{StaticResource ItemStyle}"
       Height="142"
       HorizontalAlignment="Left"
       Margin="39,30,0,0"
       VerticalAlignment="Top"
       Width="190">

       <ListBox.ItemTemplate>

          <DataTemplate>

             <StackPanel Orientation="Vertical">

                 <StackPanel Orientation="Horizontal">

                    <TextBlock
                        Text="Name:"
                        Width="50" />

                    <TextBlock
                        Text="{Binding Name}"
                        Width="150"  />

                 </StackPanel>

                 <StackPanel Orientation="Horizontal">

                    <TextBlock
                       Text="Age:"
                       Width="50" />

                    <TextBlock
                       Text="{Binding Age}"
                       Width="50"  />

                 </StackPanel>

             </StackPanel>

         </DataTemplate>

     </ListBox.ItemTemplate>

   </ListBox>
</Grid>

So I am binding the ItemsSource to the collection in the code-behind. Also notice that I am binding the style we created to the ItemContainerStyle. The DataTemplate simply creates a custom ItemTemplate to show the data.

So now if we run our code, we get this…

1

But that’s not all. Let’s say that we want to highlight the rows in different colors depending on if the name is blank or if the age is 0. We can create two separate triggers for that. We would simply change our style to this…

<Window.Resources>
   <Style TargetType="{x:Type ListBoxItem}" x:Key="ItemStyle">
       <Style.Triggers>
          <DataTrigger Binding="{Binding Name}" Value="">
               <Setter Property="Background" Value="Blue" />
          </DataTrigger>
          <DataTrigger Binding="{Binding Age}" Value="0">
               <Setter Property="Background" Value="Yellow" />
          </DataTrigger>
       </Style.Triggers>
   </Style>
</Window.Resources>

With that change, our ListBox now shows this…

2

As you can see, Data Triggers are a very powerful part of WPF. Now if only Microsoft would add this to Silverlight.

Tags: ,