Thursday, May 10, 2012

Creating and Using Collections in Silverlight

First Create generic Collection class as per your requirement in development.


public class MilesCollection : ObservableCollection<Miles>
    {
        public MilesCollection()
        {
            this.Add(new Miles(1, "1 Miles"));
            this.Add(new Miles(2, "2.5 Miles"));
            this.Add(new Miles(3, "5 Miles"));
            this.Add(new Miles(4, "10 Miles"));
        }
        public static Miles FromId(Int32 Id)
        {
            return new MilesCollection().Where(x => x.Id == Id).Single();
        }
    }
    public class Miles
    {
        public Miles()
        {

        }
        public Miles(Int32 id, String val)
        {
            Id = id;
            Value = val;
        }
        public Int32 Id { get; set; }
        public String Value { get; set; }

        public bool Equals(Miles mile)
        {
            return Id == mile.Id;
        }
    } 

as shown in above i have created Miles class and MilesCollection class that inherits from collection of Miles.

Now use your collection in UserControl or Page

<UserControl x:Class="TestApplication.Views.MileView"
       xmlns:collections="clr-namespace:TestApplication.Collections">
 
 
<ComboBox  DisplayMemberPath="Value">
           <ComboBox.ItemsSource>
               <collections:MilesCollection  />
            </ComboBox.ItemsSource
</ComboBox> 


No comments:

Post a Comment