Showing posts with label Windows Phone. Show all posts
Showing posts with label Windows Phone. Show all posts

Monday, March 19, 2012

My memo app supports multilingualization in new version 1.7














http://windowsphone.com/s?appid=01fada6f-ff7e-451b-b0b0-3bf3a5c0f655

I'm really happy to announce my memo app's new release version 1.7 !
In new version, my memo app supports multilingualization that are English and Japanese.

And second feature is that you can choose character color (black or white). You can customize character color and background color as you want.

So, please check the function in bellow Yourtube video.



Please download my memo app in your Windows Phone ! 
Thanks.

Sunday, March 18, 2012

Cannot bind two types of data source to one UI target

I was also struggling the problem when I made binding between data source and UI ListBox target.
Today, I'd like to introduce the problem that we cannot bind "non-INotifyPropertyChanged property" and "INotifyPropertyChanged property" to same ListBox target.

First, I had written property binding like this. I had used "non-INotifyPropertyChanged property".

  • The xaml code is here.
 <ListBox Height="595" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="12,6,0,0" Name="listBox1" VerticalAlignment="Top" Width="438">  
   <ListBox.ItemTemplate>  
     <DataTemplate>  
       <StackPanel HorizontalAlignment="Stretch" Orientation="Horizontal">  
         <TextBlock x:Name="Name1" FontSize="35" Text="{Binding Text1}" Foreground="Black"/>  
         <TextBlock x:Name="Name2" FontSize="35" Text="{Binding Text2}" Foreground="Black"/>  
       </StackPanel>  
     </DataTemplate>  
   </ListBox.ItemTemplate>  
 </ListBox>  
  • The code behind is here.
 public partial class MainPage : PhoneApplicationPage  
 {  
   // Constructor  
   public MainPage()  
   {  
     InitializeComponent();  
     GetList();  
   }  

   public void GetList()  
   {  
     List<ItemProperties> items = new List<ItemProperties>();  
     items.Add(new ItemProperties { Text1 = "test01", Text2 = "test02" });  
     items.Add(new ItemProperties { Text1 = "test11", Text2 = "test12" });  
     listBox1.ItemsSource = items;  
   }  
 }  

 public class ItemProperties  
 {  
   private string m_Text1;  
   public string Text1  
   {  
     get { return m_Text1; }  
     set { m_Text1 = value; }  
   }  

   private string m_Text2;  
   public string Text2  
   {  
     get { return m_Text2; }  
     set { m_Text2 = value; }  
   }  
 }  


Second, I wanted to bind Foreground color in ListBox. So, I added "INotifyPropertyChanged property" as Foreground colors.
The code is like this. But I found I couldn't bind "INotifyPropertyChanged property" to Foreground color in this code.

  • The xaml code is here.
 <ListBox Height="595" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="12,6,0,0" Name="listBox1" VerticalAlignment="Top" Width="438">  
   <ListBox.ItemTemplate>  
     <DataTemplate>  
       <StackPanel HorizontalAlignment="Stretch" Orientation="Horizontal">  
         <TextBlock x:Name="Name1" FontSize="35" Text="{Binding Text1}" Foreground="{Binding Color1}"/>  
         <TextBlock x:Name="Name2" FontSize="35" Text="{Binding Text2}" Foreground="{Binding Color2}"/>  
       </StackPanel>  
     </DataTemplate>  
   </ListBox.ItemTemplate>  
 </ListBox>  
  • The code behind is here.
 public partial class MainPage : PhoneApplicationPage  
 {  
   public ObservableCollection<ItemProperties2> ItemCollection { get; private set; }  
   // Constructor  
   public MainPage()  
   {  
     InitializeComponent();  
     GetList();  
     GetList2();  
   }  

   public void GetList()  
   {  
     List<ItemProperties> items = new List<ItemProperties>();  
     items.Add(new ItemProperties { Text1 = "test01", Text2 = "test02" });  
     items.Add(new ItemProperties { Text1 = "test11", Text2 = "test12" });  
     listBox1.ItemsSource = items;  
   }  

   public void GetList2()  
   {  
     ItemCollection = new ObservableCollection<ItemProperties2>();  
     ItemCollection.Add(new ItemProperties2  
     {  
       Color1 = new SolidColorBrush(Colors.LightGray),  
       Color2 = new SolidColorBrush(Colors.Brown)  
     });  
     ItemCollection.Add(new ItemProperties2  
     {  
       Color1 = new SolidColorBrush(Colors.Cyan),  
       Color2 = new SolidColorBrush(Colors.Red)  
     });  
     DataContext = ItemCollection;  
   }  
 }  

 public class ItemProperties  
 {  
   private string m_Text1;  
   public string Text1  
   {  
     get { return m_Text1; }  
     set { m_Text1 = value; }  
   }  

   private string m_Text2;  
   public string Text2  
   {  
     get { return m_Text2; }  
     set { m_Text2 = value; }  
   }  
 }  

 public class ItemProperties2 : INotifyPropertyChanged  
 {  
   public event PropertyChangedEventHandler PropertyChanged;  
   public ItemProperties2() { }  

   private Brush m_Color1;  
   public Brush Color1  
   {  
     get { return m_Color1; }  
     set  
     {  
       m_Color1 = value;  
       OnPropertyChanged("Color1");  
     }  
   }  

   private Brush m_Color2;  
   public Brush Color2  
   {  
     get { return m_Color2; }  
     set  
     {  
       m_Color2 = value;  
       OnPropertyChanged("Color2");  
     }  
   }  

   protected void OnPropertyChanged(string name)  
   {  
     PropertyChangedEventHandler handler = this.PropertyChanged;  
     if (handler != null)  
       handler(this, new PropertyChangedEventArgs(name));  
   }  
 } 


It seems that "non-INotifyPropertyChanged property" is given priority over "INotifyPropertyChanged property".

I think the problem is a little foolish in now. But If your code is quite large amount, you may not be able to find the problem immediately.
I write previous blog post as the answer for the problem. Please check it also.

Wednesday, March 14, 2012

Suddenly my application crashes without errors when using property binding

I introduced property binding in a previous blog post. Today, I introduce a problem when I write code of property binding.


Property binding is easy to mistake property names. If you mistake property name, you can't bind property correctly but also an application suddenly crashes without any errors.


So, please look at this code attentively. If you write such code, you can pass build action, but your application crashes suddenly without errors.

 public class ItemProperties : INotifyPropertyChanged  
 {  
   public event PropertyChangedEventHandler PropertyChanged;  
   public ItemProperties() { }  

   private string m_Text1;  
   public string Text1  
   {  
     get { return Text1; }  
     set  
     {  
       m_Text1 = value;  
       OnPropertyChanged("Text1");  
     }  
   }  

   protected void OnPropertyChanged(string name)  
   {  
     PropertyChangedEventHandler handler = this.PropertyChanged;  
     if (handler != null)  
       handler(this, new PropertyChangedEventArgs(name));  
   }  
 } 


The wrong code is here. If you write like this, your application suddenly shutdown.
get { return Text1; }  

You need to write like this.
get { return m_Text1; }  


I don't know why debugger can't catch error, but I noticed we need to pay attention when we use property binding.

Friday, March 9, 2012

Property Binding using INotifyPropertyChanged and ObservableCollection

I was struggling against property binding using INotifyPropertyChanged and ObservableCollection.
Today, I introduce how to bind from properties in a class to UI properties by using INotifyPropertyChanged and ObservableCollection. And I'll show you the problem I encountered in next blog post.


  • Sample code of property binding
I introduce a sample code binding from properties in ItemProperties class to TextBlock's properties in ListBox (One Way).

































  • The xaml code is here.
 <ListBox Height="595" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="12,6,0,0" Name="listBox1" VerticalAlignment="Top" Width="438">  
   <ListBox.ItemTemplate>  
     <DataTemplate>  
       <StackPanel HorizontalAlignment="Stretch" Orientation="Horizontal">  
         <TextBlock x:Name="Name1" FontSize="35" Text="{Binding Text1}" Foreground="{Binding Color1}"/>  
         <TextBlock x:Name="Name2" FontSize="35" Text="{Binding Text2}" Foreground="{Binding Color2}"/>  
       </StackPanel>  
     </DataTemplate>  
   </ListBox.ItemTemplate>  
 </ListBox>  
- Point - 
You need to add ItemsSource="{Binding}" in ListBx to bind properties from code behind. You also should not add like ItemsSource="{Binding Collection}", just write "{Binding}".

When you use DataTemplate in ListBox, you can't write like this in code behind.

Name1.Foreground = new SolidColorBrush(Colors.LightGray);

So you need to bind from properties as a class to UI  properties. Almost all of UI element properties (ex. Foreground, Text, any more) are implemented as dependency property. You can bind from properties as a class to UI  properties using dependency property. You can't bind using usual property.


  • The code behind is here.
 public partial class MainPage : PhoneApplicationPage  
 {  
   public ObservableCollection<ItemProperties> ItemCollection { get; private set; }  
   // Constructor  
   public MainPage()  
   {  
     InitializeComponent();  
     GetList();  
   }  

   public void GetList()  
   {  
     ItemCollection = new ObservableCollection<ItemProperties>();  
     ItemCollection.Add(new ItemProperties  
     {  
       Text1 = "test01",  
       Text2 = "test01",  
       Color1 = new SolidColorBrush(Colors.LightGray),  
       Color2 = new SolidColorBrush(Colors.Brown)  
     });  

     ItemCollection.Add(new ItemProperties  
     {  
       Text1 = "test02",  
       Text2 = "test02",  
       Color1 = new SolidColorBrush(Colors.Cyan),  
       Color2 = new SolidColorBrush(Colors.Red)  
     });  

     ItemCollection.Add(new ItemProperties  
     {  
       Text1 = "test03",  
       Text2 = "test03",  
       Color1 = new SolidColorBrush(Colors.Orange),  
       Color2 = new SolidColorBrush(Colors.Purple)  
     });  

     DataContext = ItemCollection;  
   }  
 }  

 public class ItemProperties : INotifyPropertyChanged  
 {  
   public event PropertyChangedEventHandler PropertyChanged;  
   public ItemProperties() { }  

   private string m_Text1;  
   public string Text1  
   {  
     get { return m_Text1; }  
     set  
     {  
       m_Text1 = value;  
       OnPropertyChanged("Text1");  
     }  
   }  

   private string m_Text2;  
   public string Text2  
   {  
     get { return m_Text2; }  
     set  
     {  
       m_Text2 = value;  
       OnPropertyChanged("Text2");  
     }  
   }  

   private Brush m_Color1;  
   public Brush Color1  
   {  
     get { return m_Color1; }  
     set  
     {  
       m_Color1 = value;  
       OnPropertyChanged("Color1");  
     }  
   }  

   private Brush m_Color2;  
   public Brush Color2  
   {  
     get { return m_Color2; }  
     set  
     {  
       m_Color2 = value;  
       OnPropertyChanged("Color2");  
     }  
   }  

   protected void OnPropertyChanged(string name)  
   {  
     PropertyChangedEventHandler handler = this.PropertyChanged;  
     if (handler != null)  
       handler(this, new PropertyChangedEventArgs(name));  
   }  
 } 

  • Result



Monday, January 16, 2012

How to solve the problem that you can't display a imge file from IsolatedStorage to web browser

If you have a experience that you try to display a image from IsolatedStorage to web browser as img tag, you notice you can't make it.

For instance, a image file (test.jpg) doesn't display in like html source.
 string htmlSource = @"<?xml version='1.0' encoding='utf-8'?>  
             <html>  
             <head>  
               <meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />  
             </head>  
             <body>  
               <img src='isostore:/Shared/ShellContent/test.jpg'>  
             </body>  
             </html>  
               ";  
 this.webBrowser1.NavigateToString(htmlSource);  


So, if you want to display a image file from IsolatedStorage, you need to generate Base64 String object from the image file and use Javascript to display a image file in html source code.


The sample code is like this.

  • First, generate Base64 String object from Image object.
 public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)  
 {  
  using (MemoryStream ms = new MemoryStream())  
  {  
   // Convert Image to byte[]  
   image.Save(ms, format);  
   byte[] imageBytes = ms.ToArray();  
   // Convert byte[] to Base64 String  
   string base64String = Convert.ToBase64String(imageBytes);  
   return base64String;  
  }  
 }  

  • Second, display a image using Javascript.
string base64String = ImageToBase64(image, format);  
 string htmlSource = @"<html>  
             <head>  
             </head>  
             <body>  
               <img id='icon_here'>  
               <script>  
                 var data = 'data:image/gif;base64," + base64String + @"';  
                 var icon_elem = document.getElementById('icon_here');  
                 icon_elem.src = data;  
               </script>  
             </body>  
             </html>";  
 this.webBrowser1.NavigateToString(htmlSource);  


You can display a image like this.

























If you have a great idea about the problem, please reply comment.

  • Edit. 2011/01/16
I got a comment of great idea about the problem. You don't need to use Javascript. Simply, add BASE64 string to src attribute.
 string source = @"<html>  
           <head>  
           </head>  
           <body>  
             <img src='data:image/gif;base64," + base64String + @"'>  
           </body>  
          </html>";  
 this.webBrowser1.NavigateToString(source);  

Monday, January 9, 2012

Character Corruption of Japanese Language on Web Browser

You can use build-in web browser in your application on Windows Phone. Using web browser in your app, you can display like rich text page which has images, a few fonts, javascripts or etc.

The sample code is here. 

- xaml
 <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">  
   <phone:WebBrowser HorizontalAlignment="Left" Name="webBrowser1" VerticalAlignment="Top" Height="607" Width="456" />  
 </Grid>  

- code behind
 public MainPage()  
 {  
   InitializeComponent();  
   this.webBrowser1.NavigateToString(@"  
           <?xml version='1.0' encoding='utf-8'?>  
           <html>  
             <head>  
             <meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />  
             </head>  
             <body>  
             テストページです。  
             </body>  
           </html>  
           ");  
 }  


In above sample, Japanese character is used in body in html source. If you run the program, the Japanese character should be character corruption like here.



























To solve the problem, you need to convert ASCII format to display Japanese correctly.
The sample method "ConvertExtendedASCII" is like this.
 private static string ConvertExtendedASCII(string HTML)  
 {  
   string retVal = "";  
   char[] s = HTML.ToCharArray();  
   foreach (char c in s)  
   {  
     if (Convert.ToInt32(c) > 127)  
       retVal += "&#" + Convert.ToInt32(c) + ";";  
     else  
       retVal += c;  
   }  
   return retVal;  
 }  

 public MainPage()  
 {  
   InitializeComponent();  
   string HTML = @"  
           <?xml version='1.0' encoding='utf-8'?>  
           <html>  
             <head>  
             <meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />  
             </head>  
             <body>  
             テストページです。  
             </body>  
           </html>  
           ";  
   this.webBrowser1.NavigateToString(ConvertExtendedASCII(HTML));  
 }  

The result is here.



























The ConvertExtendedASCII method takes so much time if you convert big size html. So, you need to run the method in different thread from UI thread.

Thursday, December 29, 2011

How to Generate Tile Image from StackPanel

You can make your original live tiles from your application by using StandardTileData.
But, the tile layout is limited. So, you cannot add free format text or object into live tile. The layout format is here














 If you want to add customized layout tile, you need to generate Bitmap Image using BitmapImage and WriteableBitmap and save the image into IsoratedStorage.
Please see the movie. This is from my Memo app. The movie shows that I generate a live tile from StackPanel by clicking Check Button after I change some font styles.





  • Code Sample
I introduce code sample from my Memo app. The code generates a live tile from StackPanel. Please see bellow movie.


- xaml code

The xaml code is very simple. You can change the TextBlock on the StackPanel from code.

 <StackPanel Height="173" x:Name="TilePanel" Width="173" Background="Wheat" >  
   <TextBlock x:Name="tileText" Style="{StaticResource PhoneTextNormalStyle}" HorizontalAlignment="Left" FontSize="20" TextWrapping="Wrap" />  
 </StackPanel>  


- C# code

The steps are here.

1. Create BitmapImage url.
2. Create a bitmapImage to IsolatedStorage.
3. Create a live tile using the created bitmapImage.

public static void GenerateTile(StackPanel background, string colorTitle, TextBlock tileText, string id)
{
    //Create BitmapImage url.
    //BitmapImage url should be "/Shared/ShellContent/" to share images.
    var source = new BitmapImage(new Uri("/Shared/ShellContent/", UriKind.Absolute));
    var tileImage = "/Shared/ShellContent/" + colorTitle + id + ".jpg";
    var isoStoreTileImage = string.Format("isostore:{0}", tileImage);

    //Create a bitmapImage to IsolatedStorage.
    using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        //Tile image's Height * Width are 173 * 173.
        var bitmap = new WriteableBitmap(173, 173);

        //Render a bitmap from StackPanel.
        bitmap.Render(background, new TranslateTransform());
        var stream = store.CreateFile(tileImage);
        bitmap.Invalidate();
        bitmap.SaveJpeg(stream, 173, 173, 0, 100);
        stream.Close();
    }

    //Create a live tile using the created bitmapImage.
    StandardTileData secondaryTile = new StandardTileData
    {
        BackgroundImage = new Uri(isoStoreTileImage, UriKind.Absolute),
        Title = "",
        Count = null,
    };
    //Live tile has own url.
    //You can go to your application page when you click a live tile.
    ShellTile.Create(new Uri("/Memo.xaml?id=" + id, UriKind.Relative), secondaryTile);
}


  • Reference
I questioned the topic in StackOverflow. The page is here.
A expert, his name is Claus Jørgensen, gave me excellent solution to resolve the issue. His solution is here.
He also has his code in Guthub.

Tuesday, December 27, 2011

How to Detect Clicking Hardware Back Button

You may usually want to detect clicking hareware back button on MainPage.xaml to exit your app or to resolve some paging problem.

You can detect clicking hareware back button using OnBackKeyPress method like OnNavigatedTo method. Please see bellow sample.

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}

I could pass Marketplace submission using above code.
I use the code in a page in my app because I want that it should be back to MainPage when Back Button is clicked in this page.

Sunday, December 25, 2011

Introduction of using Windows Phone Toolkit vol.5 : List Picker




Introduction of using Windows Phone Toolkit vol.1 : Download and prepare to use toolkit
Introduction of using Windows Phone Toolkit vol.2 : Tilt effect
Introduction of using Windows Phone Toolkit vol.3 : Transitions
Introduction of using Windows Phone Toolkit vol.4 : ContextMenu
Introduction of using Windows Phone Toolkit vol.5 : List Picker



Today, I introduce listpicker in Windows Phone Toolkit. I think this is most popular function in WP toolkit.
Listpicker has a lot of types of list, checkbox, listbox , combobox, etc. Let's see bellow movie and check functions.




  • Samples

Basic samples are here.

- Just choose from a list (first list on the movie)
 <toolkit:ListPicker Header="Background">  
   <sys:String>dark</sys:String>  
   <sys:String>light</sys:String>  
   <sys:String>dazzle</sys:String>  
 </toolkit:ListPicker>  


- Choose from a list of another page (second list on the movie)
<toolkit:ListPicker Header="Background" ExpansionMode="FullscreenOnly">  
   <sys:String>dark</sys:String>  
   <sys:String>light</sys:String>  
   <sys:String>dazzle</sys:String>  
   <toolkit:ListPicker.FullModeItemTemplate>  
     <DataTemplate>  
       <StackPanel Orientation="Horizontal" Margin="16 21 0 20">  
         <TextBlock Text="{Binding}"  
             Margin="0 0 0 0"  
             FontSize="43"   
             FontFamily="{StaticResource PhoneFontFamilyLight}"/>  
       </StackPanel>  
     </DataTemplate>  
   </toolkit:ListPicker.FullModeItemTemplate>  
 </toolkit:ListPicker>  

  • Sample from my memo app

I also use listpicker in my memo app.
This is color choice list. Please see bellow the movie first.




We can see same color choice list in WP toolkit sample. But the sample is little bit difficult because the sample uses DataContext and IValueConverter interface. I'll show you the simplest sample to use color choice list.


- xaml code
 <toolkit:ListPicker ItemsSource="{Binding}" Name="colorList" FullModeHeader="ACCENTS" CacheMode="BitmapCache" Width="350" SelectionChanged="ListPicker_SelectionChanged">  
   <toolkit:ListPicker.ItemTemplate>  
     <DataTemplate>  
       <StackPanel Orientation="Horizontal">  
         <Rectangle Fill="{Binding BackgroundColor}" Width="24" Height="24"/>  
         <TextBlock Text="{Binding ColorTitle}" Margin="12 0 0 0"/>  
       </StackPanel>  
     </DataTemplate>  
   </toolkit:ListPicker.ItemTemplate>  
   <toolkit:ListPicker.FullModeItemTemplate>  
     <DataTemplate>  
       <StackPanel Orientation="Horizontal" Margin="0 21 0 20">  
         <Rectangle Fill="{Binding BackgroundColor}" Width="50" Height="50"/>  
         <TextBlock Text="{Binding ColorTitle}"  
             Margin="16 0 0 0"  
             FontSize="35"/>  
       </StackPanel>  
     </DataTemplate>  
   </toolkit:ListPicker.FullModeItemTemplate>  
 </toolkit:ListPicker>  

"<toolkit:ListPicker.ItemTemplate>" indicates display format of chosen color from color list.
"<toolkit:ListPicker.FullModeItemTemplate>" indicates display format of color choice list.
Both tags have bindings of Rectangle and TextBlock which used in code behind.


- code behind
 public Tile()  
 {  
   InitializeComponent();  
   //set color list  
   List<ColorsList> list = new List<ColorsList>();  
   foreach (var c in ColorSet.ReturnColor())  
   {  
     list.Add(new ColorsList { BackgroundColor = new SolidColorBrush(Color.FromArgb(c.a, c.r, c.g, c.b)), ColorTitle = c.ColorTitle });  
   }  
   colorList.ItemsSource = list;  
}
 public class ColorsList  
 {  
   public Brush BackgroundColor { get; set; }  
   public string ColorTitle { get; set; }  
 }  

"ColorSet.ReturnColor()" returns colors set from color source of List<>.

Thursday, December 22, 2011

How to check if back button is clicked or not when page transition is occurred

In the situation of page transition, sometime you may want to check page transition is occurred by pressing back button or not.



Today I introduce how to check  if back button is clicked or not when page transition is occurred.
It's easy to make it. You can use NavigationMode Enumeration in OnNavigatedTo method. When back button is clicked, NavigationMode Enumeration should be NavigationMode.Back.

Please check bellow code sample.

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    //if the page transition is occurred by pressing back button.
    if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
    {
        //do something
    }
}

As you know OnNavigatedTo is called when page transition is occurred.

Friday, December 16, 2011

My Memo app's new version 1.2 was released !






I'm really happy to announce new version 1.2 of my Memo application !
Please download and use it !


The memo app is very fast. There is One Note in Windows Phone by default. But One Note is slow and not easy to use sometime. So, If you want to take short memo, you must use my Memo app.


  • New Features
I introduce new features of my Memo app. 

  • Colors
You can change background color in my Memo app. 
In previous version, The background color is only wheat. But you are able to choose Japanese originated colors depend on your feeling. These colors are very beautiful.

Also the tile of memo app change when you choose a color.



  • WP specific UI action
I changed user interface to Windows Phone like action. 
Please check these actions.


- Paging like shuffling through a book. 





- Click action. (tilt effect)





- Context menu when you click for a while.





You can check how to implement in your app in these blog posts.


Introduction of using Windows Phone Toolkit vol.2 : Tilt effect
Introduction of using Windows Phone Toolkit vol.3 : Transitions
Introduction of using Windows Phone Toolkit vol.4 : ContextMenu



  • Bug fixes
I fixed these bugs.

- Chinese character is showed when you use Japanese locale setting.
- Add button (+) doesn't work on Memo page.
- ApplicationBar menu on Main page has trouble seeing.


Please download and use it !

Thanks.



Wednesday, December 14, 2011

Introduction of using Windows Phone Toolkit vol.4 : ContextMenu












Introduction of using Windows Phone Toolkit vol.1 : Download and prepare to use toolkit
Introduction of using Windows Phone Toolkit vol.2 : Tilt effect
Introduction of using Windows Phone Toolkit vol.3 : Transitions
Introduction of using Windows Phone Toolkit vol.4 : ContextMenu
Introduction of using Windows Phone Toolkit vol.5 : List Picker



Today, I'd like to introduce ContextMenu. For instance, in buildin Outlook app in Windows Phone, you can find ContextMenu when you click down for a while. Please check it bellow movie.





  • How coding
First, you need to write content menu code in some control in xaml code. You can add content menu not only Button control also other controls. I introduce about Button in this part.

<Button Margin="0,0"   
     VerticalAlignment="Center"  
     Padding="12"  
     Content="ContextMenu"  
     FontSize="18">  
   <toolkit:ContextMenuService.ContextMenu>  
     <toolkit:ContextMenu>  
       <!-- You can suppress tilt on indivudal menu items with TiltEffect.SuppressTilt="True" -->  
       <toolkit:MenuItem Header="this is a menu item" Click="MenuItem_Click"/>  
       <toolkit:MenuItem Header="this is another menu item" Click="MenuItem_Click"/>  
       <toolkit:MenuItem Header="this is a yet another menu item" Click="MenuItem_Click"/>  
     </toolkit:ContextMenu>  
   </toolkit:ContextMenuService.ContextMenu>  
 </Button>  


Second, write click event code in code behind. In bellow code, adding a text which is selected in context menu to TextBlock(lastSelection).

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    lastSelection.Text = (string)((MenuItem)sender).Header;
}

Also you can use Command to bind action and use MVVM patern. I'll show you next blog post.


  • Use context menu in Listbox
I think almost of people use context menu in Listbox. I introduce how to use context menu in Listbox through my memo app. Please see bellow movie. The movie indicates you can delete selected item using context menu.





The xaml code is bellow.

 <ListBox x:Name="listBox1" ItemsSource="{Binding}" Margin="0,-20,0,0" SelectionChanged="listBox1_SelectionChanged">  
   <ListBox.ItemTemplate>  
     <DataTemplate>  
       <StackPanel HorizontalAlignment="Stretch" Orientation="Horizontal">  
         <TextBlock FontSize="35" x:Name="Title" Text="{Binding Title}" />  
         <TextBlock FontSize="25" x:Name="Date" Text="{Binding Date}" />  
         <TextBlock x:Name="Id" Text="{Binding Id}" Visibility="Collapsed" />  
         <toolkit:ContextMenuService.ContextMenu>  
           <toolkit:ContextMenu BorderThickness="0" BorderBrush="White">  
             <toolkit:MenuItem Header="delete" Click="Delete_Click"/>  
           </toolkit:ContextMenu>  
         </toolkit:ContextMenuService.ContextMenu>  
       </StackPanel>  
     </DataTemplate>  
   </ListBox.ItemTemplate>  
 </ListBox>  


The code behind is also here.

private void Delete_Click(object sender, RoutedEventArgs e)
{
    MessageBoxResult result = MessageBox.Show("do you want to delete the memo?", "Delete memo?", MessageBoxButton.OKCancel);
    if (result == MessageBoxResult.OK)
    {
        string header = (sender as MenuItem).Header.ToString();
        ListBoxItem selectedListBoxItem = this.listBox1.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
        if (selectedListBoxItem != null && header == "delete")
        {
            ItemsList list = (ItemsList)selectedListBoxItem.Content;
            items = new ItemInfo();
            items.DeleteItemFromStorage(list.Id); // delete memo from database

            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

    }
}

//binding to textblok in Listbox
public class ItemsList
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string Date { get; set; }
}


Introduction of using Windows Phone Toolkit vol.3 : Transitions












Introduction of using Windows Phone Toolkit vol.1 : Download and prepare to use toolkit
Introduction of using Windows Phone Toolkit vol.2 : Tilt effect
Introduction of using Windows Phone Toolkit vol.3 : Transitions
Introduction of using Windows Phone Toolkit vol.4 : ContextMenu
Introduction of using Windows Phone Toolkit vol.5 : List Picker



This time, I introduce Transitions. Transitions is paging from a xaml page to another xaml page like shuffling through a book. Please check bellow movie.





  • How coding
The function is also easier than other functions. You need to do things are only two steps.
First, add bellow code after phone:PhoneApplicationPage tag in your xaml page which you want to add the function. 

 
 <toolkit:TransitionService.NavigationInTransition>  
   <toolkit:NavigationInTransition>  
     <toolkit:NavigationInTransition.Backward>  
       <toolkit:TurnstileTransition Mode="BackwardIn"/>  
     </toolkit:NavigationInTransition.Backward>  
     <toolkit:NavigationInTransition.Forward>  
       <toolkit:TurnstileTransition Mode="ForwardIn"/>  
     </toolkit:NavigationInTransition.Forward>  
   </toolkit:NavigationInTransition>  
 </toolkit:TransitionService.NavigationInTransition>  
 <toolkit:TransitionService.NavigationOutTransition>  
   <toolkit:NavigationOutTransition>  
     <toolkit:NavigationOutTransition.Backward>  
       <toolkit:TurnstileTransition Mode="BackwardOut"/>  
     </toolkit:NavigationOutTransition.Backward>  
     <toolkit:NavigationOutTransition.Forward>  
       <toolkit:TurnstileTransition Mode="ForwardOut"/>  
     </toolkit:NavigationOutTransition.Forward>  
   </toolkit:NavigationOutTransition>  
 </toolkit:TransitionService.NavigationOutTransition>  


Second, change bellow code to use transitions.

RootFrame = new TransitionFrame();

  • Before
private void InitializePhoneApplication()
{
    if (phoneApplicationInitialized)
        return;

    // Create the frame but don't set it as RootVisual yet; this allows the splash
    // screen to remain active until the application is ready to render.
    RootFrame = new PhoneApplicationFrame();
    RootFrame.Navigated += CompleteInitializePhoneApplication;

    // Handle navigation failures
    RootFrame.NavigationFailed += RootFrame_NavigationFailed;

    // Ensure we don't initialize again
    phoneApplicationInitialized = true;
}

  • After
private void InitializePhoneApplication()
{
    if (phoneApplicationInitialized)
        return;

    // Create the frame but don't set it as RootVisual yet; this allows the splash
    // screen to remain active until the application is ready to render.
    RootFrame = new TransitionFrame(); /// Change the code. ///
    RootFrame.Navigated += CompleteInitializePhoneApplication;

    // Handle navigation failures
    RootFrame.NavigationFailed += RootFrame_NavigationFailed;

    // Ensure we don't initialize again
    phoneApplicationInitialized = true;
}


Also the bellow movie is my memo app using Transition.



That's all. The function is very cool. There are also other paging functions. Please check it.

Monday, December 12, 2011

Introduction of using Windows Phone Toolkit vol.2 : Tilt effect











Introduction of using Windows Phone Toolkit vol.1 : Download and prepare to use toolkit
Introduction of using Windows Phone Toolkit vol.2 : Tilt effect
Introduction of using Windows Phone Toolkit vol.3 : Transitions
Introduction of using Windows Phone Toolkit vol.4 : ContextMenu
Introduction of using Windows Phone Toolkit vol.5 : List Picker



In this blog post, I show you tilt effect that is a motion of a object sinking down when you click it.
You can check the motion in bellow movie.






  • How coding
The function is the easiest to build in your app. You just add bellow tag into all of your xaml pages.

toolkit:TiltEffect.IsTiltEnabled="True"

 <phone:PhoneApplicationPage   
   x:Class="Memo.MainPage"  
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
   xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"  
   xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"  
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
   xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"  
   mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"  
   FontFamily="{StaticResource PhoneFontFamilyNormal}"  
   FontSize="{StaticResource PhoneFontSizeNormal}"  
   Foreground="{StaticResource PhoneForegroundBrush}"  
   SupportedOrientations="Portrait" Orientation="Portrait"  
   shell:SystemTray.IsVisible="True"  
   toolkit:TiltEffect.IsTiltEnabled="True">  

Also the bellow movie is my memo app using tilt effect in listbox.


Introduction of using Windows Phone Toolkit vol.1 : Download and prepare to use toolkit











Introduction of using Windows Phone Toolkit vol.1 : Download and prepare to use toolkit
Introduction of using Windows Phone Toolkit vol.2 : Tilt effect
Introduction of using Windows Phone Toolkit vol.3 : Transitions
Introduction of using Windows Phone Toolkit vol.4 : ContextMenu
Introduction of using Windows Phone Toolkit vol.5 : List Picker


I'd like to introduce powerful tool of making Windows Phone app. The tool is Windows Phone Toolkit.
Windows Phone Toolkit has a lot of functionality that you can use Windows Phone standard UI actions, for instance, paging, click action, listbox functions, and etc.



  • Install Windows Phone Toolkit
Access the URL and download both toolkit (msi) and samples (zip).
And run msi file. After installing, you can find binaries in C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Toolkit\Oct11\Bin.


Before you start coding, you should check sample project (zip). There are cool samples and you can easily recognize the functionality.

  • Setup your project
To use Windows Phone Toolkit in your app, I'll show you short steps.

First, add reference of both Microsoft.Phone.Controls.Toolkit.dll and Microsoft.Phone.Controls.dll into your project.

C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Toolkit\Oct11\Bin\Microsoft.Phone.Controls.Toolkit.dll
C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Libraries\Silverlight\Microsoft.Phone.Controls.dll














Second, define toolkit in all of your xaml pages.

xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

 <phone:PhoneApplicationPage   
   x:Class="Memo.MainPage"  
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
   xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"  
   xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"  
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
   xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"  
   mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"  
   FontFamily="{StaticResource PhoneFontFamilyNormal}"  
   FontSize="{StaticResource PhoneFontSizeNormal}"  
   Foreground="{StaticResource PhoneForegroundBrush}"  
   SupportedOrientations="Portrait" Orientation="Portrait"  
   shell:SystemTray.IsVisible="True">  

That's all. It's very easy to start to use Windows Phone Toolkit. I'll show you functionality next blog post.

Sunday, December 11, 2011

Cannot select trial version checkbox in Market Place

When you upload your app into Market Place, sometime you cannot select trial version checkbox because the checkbox is grayout.

The most important thing is that you need to use IsTrail() method in your app if you provide trial version.


  • Try to use IsTrail() method

IsTrail() method's document is here.


Also see here.


Sample code is here.

using Microsoft.Phone.Marketplace;

        
public static bool TrialVersion;
LicenseInformation licenseInfo = new LicenseInformation();

TrialVersion = licenseInfo.IsTrial();

if (!TrialVersion)
{
    button1.Visibility = Visibility.Collapsed;
}
else
{
    button1.Visibility = Visibility.Visible;
}


When you use IsTrail() method, the method communicate with Market Place and check your status. So, you had better use IsTrail() method only once in your app.

Icons aren't display on Application Bar



There are a lot of Application Bar Icons in Windows Phone SDK (\Program Files\Microsoft SDKs\Windows Phone\v7.1\Icons)


You add icons in your project, and write bellow code. But icons aren't display by default. See above picture.


<phone:PhoneApplicationPage.ApplicationBar>  
   <shell:ApplicationBar Opacity=".5">  
     <shell:ApplicationBarIconButton Text="Email" IconUri="Icons/email.png" />  
     <shell:ApplicationBarIconButton Text="Delete" IconUri="Icons/delete.png" />  
     <shell:ApplicationBar.MenuItems>  
     </shell:ApplicationBar.MenuItems>  
   </shell:ApplicationBar>  
</phone:PhoneApplicationPage.ApplicationBar>  


Icons and other pictures Build Action is "Resource". You need to change Build Action from "Resource" to "Content" if you use theses pictures in your app.


     


After above setting, you can see icons on Application Bar.

101 Windows Phone 7 Apps Volume 1 is cool book


My best suggestion is reading this book if you have interested in developing Windows Phone Application.

  • Good points of this book
The best point of this book is a lot of tutorials are inside. You can learn step by step with building apps. The level of difficulty is up according from 1 to 50 samples.


  • Target of this book
You had better know xaml before you read this book. But you don't need to know whole sliverlight or WPF technology. Just glance basis of xaml.

Memo app for Windows Phone released


I am really excited to announce my Memo app for Windows Phone today.
http://www.windowsphone.com/ja-JP/apps/01fada6f-ff7e-451b-b0b0-3bf3a5c0f655

Please search and find my memo app in Market place, keywords are "memo", "note" like that.
You can take a short memo like iPhone memo app.

The most important thing I'd like to add is you can use trial version the most of same as functionality of full version and no limit.




  • Main page
There are notes you take. The first row of your memo is to be title. You can add new memo by + button.




  • Memo page
You can take memo on this page. Keyboard goes down when you click "Save" button.

    


  • About Updates
I'm going to add new features to memo app constantly.
And, Please don't forget rating and review. 


Thanks,