Pages

Friday, 1 June 2012

Watermark Textbox in Silverlight

Hi ,
   I was in MSDN forums and there was a question on how to create a Watermark textbox  in silverlight.  The requirement was pretty simple,
1) If the user didnt type anything , then a watermark should appear on the textbox saying "Username" . 
2) If the user types a character, it should disappear.
3) If the user deletes the content again, it should appear.

Thinking about it, it seemed pretty basic to implement.  Here was the logic i finally decided to implement.
a) Place two textboxes, one behind the other.
b) Set the background for the upper textbox to Transparent. 
c) Bind the content of the first textbox to the second textbox, using a converter.
d) The converter will check the content length in first textbox. If  length is greater than 0, it will empty the lower textblock. else it will set it to the string "Username".

Simple enough , right. Here is the code.   My project name is WaterText .

MainPage.Xaml

<UserControl x:Class="WaterText.MainPage"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WaterText"mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
 <UserControl.Resources>
<local:MyConv x:Key="myconverter"></local:MyConv>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<TextBox Height="23" HorizontalAlignment="Left" Margin="78,138,0,0" IsHitTestVisible="False" Text="{Binding ElementName=textBox2,Path=Text,Mode=OneWay,Converter={StaticResource myconverter} ,ConverterParameter='Username'}" Name="textBox1" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="78,138,0,0" Background="Transparent" Name="textBox2" VerticalAlignment="Top" Width="120" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="88,196,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
</Grid>
</UserControl>
MainPage.Xaml.cs

Just add this converter class in the code behind file. 

   public class MyConv : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string param = parameter.ToString();
            string val = value.ToString();
            if (val == "")
            {
                if (param == "Username")
                {
                    return "Username";
                }
                else
                {
                    return "Password";
                }
            }
            else
            {
                return "";
            }
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

You can see that all the requireements are satisfied now . If you want the Username to appear in a grayed out color, then change the foreground of the lower Textbox  to grey. 

Hope someone searching for this finds it useful :)

Sunday, 20 May 2012

Load PDFs to your Windows Phone

[Disclaimer :  You need to have a Developer Unlocked Phone with you for this to work  -  which means you need to have an account @ App Hub  ]

Hi people.

    I was trying to load a few of my PDF files into my windows phone.  The first obvious thing i tried was to upload them to Sky Drive and access them from there , but i realized that each time i opened the document, it was downloading from there.
 What ! My file was like 20 Mb in size, full of images and stuff that i created,  so it was taking time to download and load each time.  My next thought was like .... Write a Windows Phone App  that would contain a PDF file which i could try to access somehow.  But before i started, I thought I'll look it up on the internet instead.

To my HUGE relief, I found a damn useful tool called Windows Phone Manager Tool ,  (http://wpmanagertool.codeplex.com/releases/view/82533 )

Try it yourself.  I was able to load my Pdf files, as well as a few doc files .  I had an issue with the click once version,  so i tried the non click once  file  (which is a rar file in that codeplex site i mentioned earlier)

 So all you have to do to get a PDF loaded from your PC :

1) Get a Developer Account (Hey,come on. You need to have an unlocked phone )
2) Install WP Manager Tool (non click once version)
3) Upload files from your PC .

By the way, i developer unlocked my Phone using the Windows Phone Toolkit . I also installed the 5 apps i created . (more on Windows Phone soon) . I am so in Love with my Lumia 710 .  (Will do for now, till i get to participate in the next Contest )

P.s : Just a side note.  If you have a developer unlocked phone , and still getting the message
"Please ensure your device is PIN-unlocked and press any key to continue..."
Then all you need to do is .. wait for it. ...  remove the lock screen  on your phone  : D

Hope you found the tid bit useful !

Wednesday, 16 May 2012

Accessing local HTML files inside Silverlight OOB application

Hi Guys,
    I have been actively participating in Silverlight.net,  so i couldn't post here in the last 2 weeks.  Well the forums are amazing, you get to learn a whole lot of things there.   But first, let me tell you scenario .

A guy developed a  Html 5 application,  but he also wanted a standalone desktop application also. 
He didnt want to recode everything, so he wanted to make an OOB application that shows the HTML.
This is really a big advantage if you dont want to have internet connectivity , but still want to access that app.
After a bit of work, i finally came up with a solution that worked.    

1)  I added the Html page to my project  and changed its Build Action to "Embedded Resource".
2) Next, i tried to access that resource file path through code.
3) This is an out of browser application, so that i could use the Web Browser control.
4) I used Streams to read the data from the html resource and display it in the browser control.

It looks pretty straightforward, right :)   Here the code for the thing...

            Assembly thisAssembly = Assembly.GetExecutingAssembly();  
            string[] resNames = thisAssembly.GetManifestResourceNames(); 
            foreach (string resName in resNames)
            {
                if (resName.ToLower().EndsWith("hello.html"))  
                {
                    // To get only the file name
                    int j = resName.IndexOf('.');
                    string myres = resName.Substring(j+1);
                    
                    
                    // To get the folder where that file is present.
                    string str = Application.Current.Host.Source.LocalPath.ToString();
                    int i = str.LastIndexOf('\\');
                    str = str.Substring(0, i+1);
                    str += myres;

                    //Open the html in the browser
                    FileStream fs = new FileStream(str, FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(fs);
                    string s = sr.ReadToEnd();
                    sr.Close();
                    fs.Close();
                    webBrowser1.NavigateToString(s);
                    break;

                }
            } 
 
And so, all of you who want ot create desktop versions of Html pages can happily do so :)   

P.S :   I love the forums because you are faced with fascinating scenarios and challenges.  You could never have encountered all of them on your own . You also brush up with the basics , and more importantly , you get to know what to use in specific scenarios.

P.P.S :  I havent forgotten my agenda. I am currently working on the Silverlight Social Networking site.  Will start posting the content soon :) 

Saturday, 28 April 2012

Coming up next on Xaml and More ...

Hi Guys,
   This is just to give you the heads up on whats coming next on Xaml and more.  Instead of only showing you how to do a task, i have made up my mind to develop fairly useful applications.  They could be anything from workflow designers (he , he  i have seen lots of people with queries on that )   to social networking sites (in silverlight , of course)

We will explore a vast combination of things related to Silverlight .
Well, maybe not that vast, but still you'll be able to understand it pretty fast.
Here are few of the things we'll dive deep into .

1) Silverlight pivot viewer
2) Bing Maps
3) MVVM ,Prism
4) Silverlight Business Applications
5) Custom controls
6) Windows Phone Apps.
7) XNA  ( i think it comes in the more part  of Xaml and more ...)
8) 3D in silverlight
9) Windows 8 development

We will create several applications through this journey , and i hope it will be a great learning experience for both you and me.
In case you find anywhere that things can be done in a better way in my code, please offer your valuable suggestions , and we will try to improve .

 Some of the ones in my mind are

1) A Workflow creator.
2) A Social networking site.
3) A Chat client (Maybe we can explore networking and stuff here)
4) A Silverlight Content Management System ( a basic one, but should get you going)
5) An Online examination Portal
6) An Image editor in Silverlight (where we can try our hand at Bitmaps and layers and cool stuff)

I am going to start making the video tutorials and podcasts in parallel . So keep waiting for a few more days.  Meanwhile you guys could keep encouraging me by giving new ideas for the tutorials  :D

And from now onwards, i will try to post my code samples on Sky Drive and share them here.

Bindings in Silverlight - Bonus post :)

Hi ,
  I was just experimenting with the listbox and combobox ,and decided to combine and use the two together. 
 Effectively,  I want to have a listbox , which contains several combo boxes instead of regular text. 

 And it should all be done with data binding.

So the first step is to create sample data.
 With this requirement in mind, i  decided to create a few classes.

  public class MyObject
    {
        public int Id { get; set; }
    }

  public class encaps
    {
        public List<MyObject> mylist{get;set;}
    }

 As you can see, the data i want to display in the ComboBoxes are integers.  The objects of encaps will be the ItemSource for the Listbox .

We need to bind data to the listbox, and each of that data inturn should be bound to a combo box. So we make use of List<> collection. Create the sample data as shown below.


         List<encaps> l = new List<encaps>();

            for (int j = 0; j < 10; j++)
            {
                List<MyObject> myo = new List<MyObject>();
                for (int i = 0; i < 10; i++)
                {
                    MyObject m = new MyObject();
                    m.Id = i*j;
                    myo.Add(m);
                }
                encaps e = new encaps();
                e.mylist = myo;
                l.Add(e);
            }

            listBox1.ItemsSource = l;
         
The second step is to  create Data templates for the listbox and combobox to display the items.   So you need to change the xaml accordingly.


  <ListBox Height="193" HorizontalAlignment="Left" Margin="48,28,0,0" Name="listBox1" VerticalAlignment="Top" Width="325" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <ComboBox ItemsSource="{Binding Path=mylist}" >
                        <ComboBox.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Width="35"  Height="35" Text="{Binding Path=Id}" />
                            </DataTemplate>
                        </ComboBox.ItemTemplate>
                     </ComboBox>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>


Observe the bindings here.  The property Id is retrieved from the mylist because the Combobox is exposing that to the TextBlock.    We get our required output, without much effort at all  :)  This can be great for scenarios where you need to show multiple combo boxes . And that's it. We are done .



I haven't changed the width of the combo boxes. You can set them in the Xaml for a nice look and feel.
This same scenario can be done for a data grid also. Just try experimenting and see if it works . All the best :)

Monday, 23 April 2012

Bindings in Silverlight - Binding to ListBox

Hi, and welcome back.  this is the last post of the Bindings in Silverlight Mini Series .  In this we will see how we can bind data to the ListBox. We will make use of Templates for customising the display.

1) We will write the familiar classes - One for providing us the data and one for the Converter

  public class Vals
    {
        public int val1 { get; set; }
        public int val2 { get; set; }
        public  Vals(int n1,int n2)
        {
        val1 = n1;
        val2 = n2;
        }
    }


    public class MyConv : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            int i = Int32.Parse(value.ToString());
            if ( i > 6  &&  i % 5  != 0  &&i  <14  )
            {
                return "Red";
            }
            else if (i < 10)
            {
                return "Blue";
            }
            else
            {
                return "Green";
            }
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }


2) Now that we have them in place, lets go and add ListBox to the Xaml , and use an ItemTemplate  to customise it.

 <ListBox Height="345" HorizontalAlignment="Left" Margin="24,12,0,0" Name="listBox1" VerticalAlignment="Top" Width="255" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel >
                        <TextBox  Background="{Binding Path=val1, Converter={StaticResource myConvStatic} }" Text="{Binding val1}" Width="50"></TextBox>
                        <TextBox Background="{Binding Path=val1, Converter={StaticResource myConvStatic} }" Text="{Binding val2}" Width="50"></TextBox>
                  </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>


3)  As you can see , the ItemTemplate of the ListBox contains a DataTemplate tag.  It is the model for how your data should be presented. It can contain only one item , so we use a StackPanel /grid/Canvas  type of structure, to add multiple items .  In case you only want a single item like a textbox, then we can use that directly.

4)   Now add some data to your program in the MainPage constructor
  
           List<Vals> a = new List<Vals>();
            for (int i = 1; i < 10; i++)
            {
                a.Add(new Vals(i*2,i*5));
            }
            listBox1.ItemsSource = a;

Run your program  and you will see the following output.

This ends this Mini Series. Hope you enjoyed the bindings in Silverlight.

Bindings in Silverlight - binding Textbox to a Datagrid

Hi , and welcome back. Now that you have seen how to bind data to controls, we will now see how to bind data from one control to another control.  This is an extension of what we have already done.  To bind one control to another , we use the ElementName and Path  properties of the Binding.

So Lets start by creating a DataGrid, and a TextBox .   In the code, create a list of numbers to use as data for the DataGrid.  

List<int> a = new List<int>();
for (int i = 1; i < 10; i++)
{
  a.Add(i *2);
}
dataGrid1.ItemsSource = a;


Now , In the Xaml , write the following binding for the Text property of the TextBox

Text="{Binding ElementName=dataGrid1, Path=SelectedItem}"
If you observe, we are using the ElementName to specify the element to which this is bound , and the path to specify which property of the element it is bound to.  Currently, i have chosen to use the SelectedItem property.   It is very important that all properties are CaseSensitive. In case you misspell, it will not cause any excaption, but it will not display anything either.


Now we need to talk a little about binding Modes .  there are 3 modes for binding in silverlight :
1)One time   2)One Way  3)TwoWay

Lets say you have two textboxes A and B to illustrate
A has the text "A" , and B is empty "".

In One Time, you obviously understood, that data is bound only once while the control is loading , and then there is no binding between the elements.  So when it loads, the content of B becomes A , and then if you  change the text of A , the value in b doesn't change.

In One way binding, which is the default option, you can always get the updated value to the bound element .  In one way binding, whatever the value of A , that value of B is also the same.However, if you change the value of B, there is no change in A.

In Two Way binding, change in value of any of the element results in a change in the value of the other.  For example , any change to A is accompanied by a change to B, and vice versa.

Now to make things more interesting with a demo , so add another TextBox to the screen.  Lets bind this to the textBox1's text property.  and set the mode to TwoWay.
 So for the textBox2 's  text property,

 Text="{Binding ElementName=textBox1, Path=Text,Mode=TwoWay}"
 Now any change to textbox2 should change textbox1.

You can notice a few things additionally in this example.
When you click on the datagrid values as the application loads , the contents of both the  textboxes change.
When you change the content of textBox 1, the contents of textbox2 change.



However, when you change the contents of textbox2 , and then click on the datagrid, the binding to the datagrid wont be valid. Clicking on 12 in dataGrid will not change the data in the textBoxes.

 Just experiment with the bindings with other controls and see more features of binding. In hte next post, we will use bindings and converters to change the color of the listboxes.  And that will be the last post of this mini series on basic bindings . See you next time.