Random programming things I'd want to remember

Showing posts with label windows-phone-7. Show all posts
Showing posts with label windows-phone-7. Show all posts

Wednesday, January 2, 2013

Simple MVVM tutorial for Windows Phone explained

Once I started learning MVVM pattern for Windows Phone, I decided to write a short sample demonstrating all the features so that I can sum it up for myself. Here it is. This article was a great starting point to understand MVVM. The most important thought I got out of that article was the INotifyProperty changed interface, which allows the controls on the phone be notified about the changes in the elements that they are bound to. We'll start with the view:
<!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="0.5*"/>
                <ColumnDefinition Width="0.5*"/>
            </Grid.ColumnDefinitions>

            <Button Content="{Binding OneText}" Command="{Binding OneCommand}" IsEnabled="{Binding IsButton1Enabled}" />
            <Button Content="{Binding TwoText}" Command="{Binding TwoCommand}" IsEnabled="{Binding IsButton2Enabled}" Grid.Column="1" />
        </Grid>


There are many ways to hook up ViewModel to the View. This is the simplest one:
        public MainPage()
        {
            InitializeComponent();
            this.DataContext = new OneViewModel();
        }


The idea behind the app is very simple: there are two buttons, pressing one of them deactivates it and activates the other. It also changes the Content property of the other button. So my ViewModel should expose two properties for buttons' contents, two commands, and two properties for buttons' enabled/disabled status. Let's get to it. By the way, Random class will be my model, it will provide Content for buttons.
//ViewModel
    public class OneViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        Random r;

        private string _oneText;
        public string OneText
        {
            get { return this._oneText; }
            set
            {
                if (value == this._oneText)
                    return;
                this._oneText = value;
                this.OnPropertyChanged("OneText");
            }
        }

        private string _twoText;
        public string TwoText
        {
            get { return this._twoText; }
            set
            {
                if (value == this._twoText)
                    return;
                this._twoText = value;
                this.OnPropertyChanged("TwoText");
            }
        }

        private bool _isButton1Enabled;
        public bool IsButton1Enabled
        {
            get { return _isButton1Enabled; }
            set
            {
                if (_isButton1Enabled == value)
                    return;
                _isButton1Enabled = value;
                this.OnPropertyChanged("IsButton1Enabled");
            }
        }


        private bool _isButton2Enabled;
        public bool IsButton2Enabled
        {
            get { return _isButton2Enabled; }
            set
            {
                if (_isButton2Enabled == value)
                    return;
                _isButton2Enabled = value;
                this.OnPropertyChanged("IsButton2Enabled");
            }
        }

        private DelegateCommand _oneCommand;
        private DelegateCommand _twoCommand;
        
        //Constructor
        public OneViewModel()
        {
            r = new Random(); //This is my model
            IsButton1Enabled = true;
            IsButton2Enabled = false;
            OneText = r.Next(100).ToString();
            TwoText = r.Next(100).ToString();
            _oneCommand = new DelegateCommand(this.OneCommandAction);
            _twoCommand = new DelegateCommand(this.TwoCommandAction);
        }

        private void TwoCommandAction(object obj)
        {
            OneText = r.Next(100).ToString();
            IsButton1Enabled = true;
            IsButton2Enabled = false;
        }

        private void OneCommandAction(object obj)
        {
            TwoText = r.Next(100).ToString();
            IsButton1Enabled = false;
            IsButton2Enabled = true;
        }

        public ICommand OneCommand { get { return _oneCommand; } }
        public ICommand TwoCommand { get { return _twoCommand; } }

        private void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }



Not much to explain here, everything seems pretty obvious and simple. As I said before, the this.OnPropertyChanged(...) methods letting the View know that things change and the View adjusts accordingly.

Here is the definition for the DelegateCommand class.


    public class DelegateCommand : ICommand
    {
        Func<object, bool> canExecute;
        Action<object> executeAction;

        public DelegateCommand(Action<object> executeAction)
            : this(executeAction, null)        {        }

        public DelegateCommand(Action<object> executeAction, Func<object, bool> canExecute)
        {
            if (executeAction == null)
            {
                throw new ArgumentNullException("executeAction");
            }
            this.executeAction = executeAction;
            this.canExecute = canExecute;
        }

        public bool CanExecute(object parameter) //can command execute in its current status?
        {
            bool result = true;
            Func<object, bool> canExecuteHandler = this.canExecute;
            if (canExecuteHandler != null)
            {
                result = canExecuteHandler(parameter);
            }
            return result;
        }

        public event EventHandler CanExecuteChanged; //occurs when changes occur that affect whether or not the command should execute

        public void RaiseCanExecuteChanged()
        {
            EventHandler handler = this.CanExecuteChanged;
            if (handler != null)
            {
                handler(this, new EventArgs());
            }
        }

        public void Execute(object parameter) //Method to call when the command is invoked
        {
            this.executeAction(parameter);
        }
    }

        


A couple of points of interest. If your buttons don't seem like they are reacting to the commands and you think everything is hooked up properly, check to make sure your ViewModel class is declared as public.

This site has videos on MVVM implementation for more serious things like, navigation and so on.

Also, be sure to check out my other article on MVVM where I implement a simple keyboard on Windows Phone. That tutorial is easier than this one.

For another tutorial, be sure to check my other article on the subject.


Monday, December 3, 2012

Today I learned (December 3, 2012)


Today I learned how to access StaticResource resources from xaml.cs codebehind files. This is how I'd return the regular PhoneForegroundBrush color from an IValueConverter:
return App.Current.Resources["PhoneForegroundBrush"] as SolidColorBrush;


And this is how I would emphasize text with the phone accent color.
return App.Current.Resources["PhoneForegroundBrush"] as SolidColorBrush;


Sources: source 1, source 2

Monday, July 30, 2012

Solving the size limitation of controls in Windows Phone 7


There is a limitation on a size of a control in Windows Phone 7 of 2048 pixels, and I needed to sometimes display a long list of items. Here is how I did that. First off, the XAML portion:

<ScrollViewer Tap="ScrollViewer_Tap" Name="AnswerScrollViewer" 
                          Grid.Row="1" Height="Auto">
    <StackPanel x:Name="AnswerScrollViewerStackPanel">
        <TextBlock x:Name="Answer"  
                      Width="430"
                      Text=""
                      Tag=""
                      FontSize="28" 
                      TextWrapping="Wrap" />
    </StackPanel>
</ScrollViewer>

There is a ScrollViewer that I use to scroll a long list. It has a StackPanel (because ScrollViewer can only have one control inside it, and I will use several controls to display a long list of text). Then the StackPanel has the "Answer" TextBlock control that is used when there is no need to display the long list.

And now, on to the magic. This is a part of the function that assigns the text to the text block.


//more on the MeasureSizeOfATextBlock() later
double futureAnswerTextBlockSize = MeasureSizeOfATextBlock(Answer, Answer.Tag.ToString());

//MAXCONTROLHEIGHT is a constant, close to 2048
if (futureAnswerTextBlockSize > MAXCONTROLHEIGHT)
{    //I split my string by the carriage returns
    string[] options = { "\r\n" };
    string[] arr = Answer.Tag.ToString().Split(options, StringSplitOptions.None);

//Let's create the first text block to start displaying the list
    TextBlock b = new TextBlock();
    b.Foreground = DarkThemeIsVisible() //more on this function later
        ? new SolidColorBrush(Color.FromArgb(255, 255, 255, 255))
        : new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
    b.VerticalAlignment = System.Windows.VerticalAlignment.Top;
    b.FontSize = ANSWERTEXTFONTSIZE;
    b.TextWrapping = TextWrapping.Wrap;
    b.Width = 430;
    b.Name = "sb1"; //the name really does not matter

    int j = 0;
//This constant will help me omit the new line before the first line of text
    bool omitCRForNewLine = true;
//and let's display the text
    while (j < arr.Length)
    {
        if (!omitCRForNewLine)
            b.Text += Environment.NewLine + arr[j];
        else
            b.Text += arr[j];

        omitCRForNewLine = false;

        j += 1;
        if (b.ActualHeight > MAXCONTROLHEIGHT - 20)
        { //The height of the control is getting closer to the limit
//so let's add this control to the stack panel, and ...
            AnswerScrollViewerStackPanel.Children.Add(b);
//create a new control to continue displaying the text
            b = new TextBlock();
            b.Foreground = DarkThemeIsVisible()
                ? new SolidColorBrush(Color.FromArgb(255, 255, 255, 255))
                : new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
            b.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            b.FontSize = ANSWERTEXTFONTSIZE;
            b.TextWrapping = TextWrapping.Wrap;
            b.Width = 430;
            b.Name = "sb" + j.ToString();
//reset this variable to avoid the empty line in the beginning
            omitCRForNewLine = true; 
        }

        if (j == arr.Length - 1) //add the last text block
            AnswerScrollViewerStackPanel.Children.Add(b);

    } //hide Answer text block, I am not using it
    Answer.Visibility = System.Windows.Visibility.Collapsed;
}
else
{ //if one text block is enough, everything is simple
    Answer.Visibility = System.Windows.Visibility.Visible;
    Answer.Text = Answer.Tag.ToString();

    Answer.Foreground = DarkThemeIsVisible()
        ? new SolidColorBrush(Color.FromArgb(255, 255, 255, 255))
        : new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
    Answer.VerticalAlignment = System.Windows.VerticalAlignment.Top;

    Answer.FontSize = ANSWERTEXTFONTSIZE;
}


And here are the two helper functions. The first function takes a control as input, and a line of text. Then it creates a TextBlock, assigns some parameters and returns the ActualHeight parameter of the control.

private double MeasureSizeOfATextBlock(TextBlock t, string text)
{
    TextBlock a = new TextBlock();
    a.Width = t.Width;
    a.FontFamily = t.FontFamily;
    a.FontStyle = t.FontStyle;
    a.FontWeight = t.FontWeight;
    a.FontSize = t.FontSize;
    a.Text = text;
    a.TextWrapping = t.TextWrapping;

    return a.ActualHeight;
}



This function determines whether the user has the dark or light theme selected.

private bool DarkThemeIsVisible()
{
    Visibility v = (Visibility)Resources["PhoneDarkThemeVisibility"];
    if (v == System.Windows.Visibility.Visible)
        return true;

    return false;
}




Friday, July 20, 2012

Windows Phone 7 ItemsControl within an ItemsControl, solving slow loading issue


So it happened that I needed to show a long list within a long list. I found that the scrolling performance of a ListBox was not up to par, so I tried an ItemsControl. Here is the XAML:


<ItemsControl 
    MaxWidth="450" VirtualizingStackPanel.VirtualizationMode="Recycling"
    ItemsSource="{Binding AnswersForDisplayAsAListBySomeNumberOfElements}"
    Visibility="{Binding ThisOneHasALongAnswer, Converter={StaticResource showLongAnswer}}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <<ItemsControl.Template>
        <ControlTemplate>
            <ScrollViewer x:Name="InnerScrollViewer" Padding="{TemplateBinding Padding}" MaxHeight="400">
                <ItemsPresenter />
            </ScrollViewer>
        </ControlTemplate>
    </ItemsControl.Template>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" TextWrapping="Wrap" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Upon binding, if the ItemsList is visible, it displays a scrollable list. The problem with this approach is that once the inner list is scrolled to the bottom (or to the top), the outer ItemsList is not being scrolled. After playing with it for a bit, I figured out that if the ScrollViewer is removed from the ItemsControl.Template part of the control declaration, then the long list is displayed in its entire height and scrolling the individual item scrolls the entire outer ItemsList

Sunday, July 15, 2012

Extract data from an app in Windows Phone 7


I needed to export some text data out of one Windows Phone 7 application. I did not care for the format, so I thought e-mailing data to myself would be just fine. Here is some code. First, let's build the data:

public StringBuilder GetData()
{
  StringBuilder result = new StringBuilder();

  List<InventoryItem> a = ReadInventoryItems().OrderBy(x=>x.SerialNumber).OrderBy(x => x.Account).Where(x => x.isFound == true).ToList<InventoryItem>();

  foreach (InventoryItem i in a)
  {
    LocatedItem l = new LocatedItem { 
        Account = i.Account, 
        SerialNo = i.SerialNumber, 
        wasFound = i.isFound, 
        withNote = i.Note 
    };
    result.Append(l.ToString() + Environment.NewLine);
  }
  return result;
}



InventoryItem and LocatedItem are just two classes that I use to store data:
public class InventoryItem
{
    public string SerialNumber { get; set; }
    public string Account { get; set; }
    public string ModelDesc { get; set; }
    public string Building { get; set; }
    public string Room { get; set; }
    public string BuildingRoom { get; set; }
    public bool isFound { get; set; }
    public string Note { get; set; }
}

 public class LocatedItem
 {
     public string Account {get; set;}
     public string SerialNo { get; set; }
     public bool wasFound { get; set; }
     public string withNote { get; set; }

     public override string ToString()
     {
         return String.Format("{0} {1} {2} {3}", Account, SerialNo, wasFound == true ? "1" : "0", withNote);
     }
 }


Data is ready, how to extract it? The help comes from EmailComposeTask class that resides is the Microsoft.Phone.Tasks namespace. Here is some code:
EmailComposeTask email = new EmailComposeTask();
emailcomposer.To = @"youraddress@yourmailserver.com";
emailcomposer.Subject = "test subject";
DataLayer dl = new DataLayer();
emailcomposer.Body = dl.GetAllFoundItems().ToString();
emailcomposer.Show();


And that is it! Once deployed to the phone, choose the e-mail provider that will send the message and send the e-mail.

Wednesday, March 21, 2012

Error: To generate an event handler the class 'MainPage', specified by the x:Class or x:Subclass...

I was testing something out on the Windows Phone 7 platform and, when tried to add a button Click event, Visual Studio 2010 gave me the following error: To generate an event handler the class 'MainPage', specified by the x:Class or x:Subclass attribute, must be the first class in the file. Move the class code so that it is the first class in the file and try again. This is what my MainPage.xaml.cs file looked like:

public class TestItem { public string Name { get; set; } public int Count { get; set; } } public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage() { InitializeComponent(); List<TestItem> li = new List<TestItem>(); TestItem a = new TestItem { Name = "First name", Count = 1 }; TestItem b = new TestItem { Name = "Second name", Count = 2 }; TestItem c = new TestItem { Name = "Third name", Count = 3 }; listBox1.DataContext = li; } }
Then I realized that I put together a dummy class to test binding on a ListBox and put it on the top of the document. Once I moved the TestItem class definition down, the page compiled and I was able to add events from the XAML page. Here is what the working code looks like:

public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage() { InitializeComponent(); List<TestItem> li = new List<TestItem>(); TestItem a = new TestItem { Name = "First name", Count = 1 }; TestItem b = new TestItem { Name = "Second name", Count = 2 }; TestItem c = new TestItem { Name = "Third name", Count = 3 }; listBox1.DataContext = li; } private void btn1_Click(object sender, RoutedEventArgs e) { } } public class TestItem { public string Name { get; set; } public int Count { get; set; } }

Tuesday, March 6, 2012

Windows phone review after a month of use by an iPhone user (Samsung SGH-i917)


I have a Samsung SGH-i917 (a Windows 7 phone) and I would like to share my experience of using it in case someone is thinking about getting a Windows 7 phone. For the record, I have used an iPhone for several years and it influenced my mobile phone usage. I am not, in any way, against Windows 7 Phone platform, I just want to point out things that could use some more work.

Turning on the phone. This phone is light and thin, which makes it harder to find the power button, and that is the only way to turn on the phone or wake it up. It is hard to tell in the dark which way is up or down, that may increase the time needed to find the power button.

E-mail setup. For some reason, I have to set up the phone with a Windows Live ID. I have an old e-mail associated with Windows Live ID, it has a lot of my old contacts. The phone insisted that I associate a Live ID with it. Ok, I did that. It immediately imported all my contacts from that phone. It would be nice if the phone asked me if I want all those contacts imported. Now I am stuck with a long list of people in my phone that I no longer even talk to. Setting up additional e-mails is very easy. Getting rid of e-mail accounts is a bit tricky. First of all, I cannot get rid of the Live ID e-mail account. Second, if I need to get rid of any other e-mail, I had to click and hold the e-mail account to get the context menu. It took me a bit to figure that out, it would be nice to have a hint or buttons on the bottom. Also, with e-mail (I tried hotmail and gmail), if I delete an e-mail on the phone, it would still be in the mailbox once I use the computer to log in. A matter of preference, really.

Adding a phone contact. This process is the most frustrating for me. I usually type the phone number, press save, expect to type in the name and maybe some other info and then I am done. Here are the steps that one need to take to save a phone number on Windows 7 Phone:
1. Type in the phone number (ok so far).
2. Hit save button. Boom! I suddenly see my contact list. Why? Oh, they assume that my friends buy new phone numbers every week. No, actually my contacts are pretty conservative on their phone numbers. So how do I add a new number? Oh, there is a small plus button on the bottom.
3. Press the + button on the bottom.
4. I see the phone number box, I see the type of the phone. Where do I type in the name? And the number keyboard takes up half the screen. But I already typed in the number! Oh, there is a button on the bottom that looks like a … floppy disk? Who remembers what those are anymore?
5. Let's hit the "floppy disk" button. I see the page, big box to add photo, I see a label for the name, mobile phone (and the phone itself is in the tiny numbers, so if I fat-fingered it, no way I can notice the mistake), phone, email, … how do I type in stuff? Oh, there is a "plus" button to the left of each label, while I was expecting a text box…
6. Let's hit the "plus" button. Yay! I can type in the name! And the floppy disk icon on the button again… oh, they used it to save data before, that symbol must mean "save"!
7. Type the name
8. Hit the floppy disk button to save the name
9. Hit the floppy disk button to save the contact
10. Yay, I saved a contact! The phone number is still small, but it is a very important piece of info.

One contact, but I had to hit save button four times! My ideal way to save a contact is the following:

1. Type in the phone number
2. Hit save button
3. Get presented with fields for the new contact (phone number must be in BIG numbers so that I can double-check it with whoever is giving it to me). If I need to add the phone number to an existing contact, give me a button in top right corner. 
4. Fill in all the info
5. Hit save button.

Wi-Fi. I hooked up the phone to wireless internet, that was easy. However, the phone only displays the Wi-Fi connection icon on the home screen. When I am browsing Internet, I don't see the Wi-Fi icon and I am not sure whether I use my cellular plan or Wi-Fi to get that web page. Same with e-mail. It just says "Syncing", but does not show what connection it uses. This matters for me, I was using a prepaid cell phone plan, did not want to run out of money.

Battery indicator. The phone has information on the remaining battery in percents, as well as approximate time of service remaining until it absolutely needs to be charged. The battery icon in top right, however, cannot be customized to display percents. This is also a matter of preference, but I would prefer to see the percentage of remaining battery power.

Search. The built-in search feature is mostly nice. If I search for "weather" it gives me weather at a glance in my location. But when I try searching for "las vegas weather" (I am not in Las Vegas), it gets stuck searching. I tried restarting search and still no answer. Why? Not sure. May be this is a hardware issue. The other nice feature is built-in search for music, scanner, and voice-activated search. However, there are still issues here. I was listening to the radio and used the "search for music" feature. The radio kept playing and the phone kept listening. I cancelled the searched after about a minute. I sure wasn't turning the radio off. Text/barcode/QR code scanner works great. Oh, one other thing on the search: splitting results into web/local/images, what is "local" supposed to be? I am searching for "weather", swipe to local and I see a small piece of map (I can't make out what that location is, anyway, the map is too small), and the map points to the place called "Time Temperature & Weather". Not sure what it is. Works somewhat better when I search for "farmers market", the results make a bit more sense.

Maps, directions. There are two issues here. First, after I found my route and just want to browse the map along the way, the map keeps returning me where it thinks I am at at the moment. I just want to browse the map before I drive, to see the traffic and other things, don't change my map! The other thing about this area is that once I get directions to some place and hit the back button, directions disappear. That is ok. Another scenario: I find directions, move the maps application to the background, then start it again and hit the back button, what happens? Right, instead of clearing the directions from the map, the phone shows me the screen that I was at before.

Buttons. Home key, once pressed, provides slight vibration feedback; nice feature.

Size. The phone feels wide, thin and light.

Camera. Nice camera, takes good pictures, have some additional features, such as effects and even the white balance correction.

Marketplace. Feels cluttered. When I am choosing an item, I would like to see how much it costs right away, without having to tap on it.

Overall, I think this phone and the platform itself could use some more work. Great job on the concept though, I very much like the fact that I can use C# and put my programs right on to the phone.

Saturday, July 2, 2011

Windows Phone 7: Iterate over ListBoxItems in a list box to focus on a control

I am developing a small Windows Phone 7 application and I ran into a wall. I am updating items within a ListBox and I need to set focus on a control after the update. It turns out that it is not a trivial task -- I need to iterate over the entire list box to get to the control and then set focus on it.

Here is the XAML of my list box:

     
                
                    
                        
                            
                            
                            
                        
                    
                

            

I was using the VisualTreeHelper class to iterate over the ListBox, but I was not getting to the ListBoxItems. I was getting ListBox, ScrollViewer, Border, Grid, ContentPresenter, ItemsPresenter, VirtualizingStackPanel, and other controls, but no ListBoxItems. After reading this, the problem was fixed by calling the
UpdateLayout
method. The rest was simple. Here is my code.

void SetFocusOnTextBox(DependencyObject element, int primaryKey)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                if (foundItem == false) //global flag that stops processing once the control is found
                {
                    DependencyObject child = VisualTreeHelper.GetChild(element, i);
                    StackPanel s = child as StackPanel;
                    if (s != null)
                        FindAllChildrenOfAStackPanel(child, primaryKey);
                    if (foundItem == false)
                        SetFocusOnTextBox(child, primaryKey);
                    else
                        break;
                }
            }
            foundItem = false;
        }

        void FindAllChildrenOfAStackPanel(DependencyObject element, int primaryKey)
        {
            StackPanel s = element as StackPanel;
            if (s != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
                {
                    TextBox t = VisualTreeHelper.GetChild(element, i) as TextBox;
                    if (t != null)
                        if (t.Name == primaryKey)
                        {
                            t.Focus();
                            foundItem = true;
                            break;
                        }
                }
            }
        }