top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Auto Complete in DataGrid Cell Editing in Silverlight 3 Application

+4 votes
143 views

Introduction

In this article we will see how we can implement AutoComplete feature in a cell editing in DataGrid.

Creating Silverlight Project

Fire up Visual Studio 2008 and create a Silverlight Application. Name it as AutoComlpeteDataGridInSL3.

1.gif
 
Go ahead and add a DataGrid to your application.

2.gif
 
Now add a Class to define properties for sample data.

public class Users: INotifyPropertyChanged
    {
        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

 

        #region UserName

        private string _UserName;

        public string UserName

        {

            get { return _UserName; }

            set

            {

                if (value.Length < 4)

                {

                    throw new ValidationException("User Name should contain atleast 4 chars");

                }

                _UserName = value;

                RaisePropertyChanged("UserName");

            }

        }

        #endregion

 

        #region Age

        private int _Age;

        public int Age

        {

            get { return _Age; }

            set

            {

              _Age = value;

            }

        }

        #endregion

 

        #region Gender

        private string _Gender;

        public string Gender

        {

            get { return _Gender; }

            set

            {

                _Gender = value;

            }

        }

        #endregion

 

        #region Country

        private string _Country;

        public string Country

        {

            get { return _Country; }

            set

            {

                _Country = value;

            }

        }

        #endregion       

 

        private void RaisePropertyChanged(string propertyName)

        {

            if (this.PropertyChanged != null)

            {

                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

            }

        }

    }

Now add some sample data to a List and assign the list to the ItemSource of the DataGrid.

public MainPage()
        {

            InitializeComponent();

            List<Users> myList = new List<Users>

            {

                new Users{ UserName="Hiro Nakamura", Age=24, Gender="M", Country="Japan"},

                new Users{ UserName="Mohinder Suresh", Age=26, Gender="M", Country="India"},

                new Users{ UserName="Claire Bennette", Age=20, Gender="F", Country="USA"},

                new Users{ UserName="Matt Parkman", Age=30, Gender="M", Country="USA"},

                new Users{ UserName="Nathan Patrelli", Age=30, Gender="M", Country="USA"},

                new Users{ UserName="Peter Patrelli", Age=26, Gender="M", Country="USA"},

                new Users{ UserName="Mica Sanders", Age=19, Gender="M", Country="USA"},

                new Users{ UserName="Linderman", Age=56, Gender="M", Country="USA"},

                new Users{ UserName="Ando", Age=24, Gender="M", Country="Japan"},

                new Users{ UserName="Maya", Age=24, Gender="F", Country="Mexico"},

                new Users{ UserName="Angela Patrelli", Age=26, Gender="F", Country="USA"},

                new Users{ UserName="Niki Sanders", Age=26, Gender="F", Country="USA"},

            };

 

            MyDataGrid.ItemsSource = myList;

        }

Now that you have added some sample data, you can test your application.

3.gif
 
Now we don't need to have AutoGenerateColumns of the DataGrid as we are going to define our own.

Follow the xaml code behind for a template:

<data:DataGrid x:Name="MyDataGrid" Margin="0" Grid.Row="1" Grid.Column="1"IsReadOnly="False" AutoGenerateColumns="False">

            <data:DataGrid.Columns>

                <data:DataGridTextColumn Binding="{Binding Age}" Header="Age" />

                

                <data:DataGridTemplateColumn Header="User Name">

                    <data:DataGridTemplateColumn.CellTemplate>

                        <DataTemplate>

                            <TextBlock Text="{Binding UserName}" Margin="4" />

                        </DataTemplate>

                    </data:DataGridTemplateColumn.CellTemplate>

                    <data:DataGridTemplateColumn.CellEditingTemplate>

                        <DataTemplate>

                            <input:AutoCompleteBox

                                    HorizontalAlignment="Left"

                                    Width="180"

                                    IsTabStop="True"

                                    Text="{Binding UserName, Mode=TwoWay}"

                                    ItemsSource="{StaticResource SampleHeroes}"

                                    />

                        </DataTemplate>

                    </data:DataGridTemplateColumn.CellEditingTemplate>

                </data:DataGridTemplateColumn>

                <data:DataGridTextColumn Binding="{Binding Gender}" Header="Gender" />

                <data:DataGridTextColumn Binding="{Binding Country}" Header="Country" />

            </data:DataGrid.Columns>

 

        </data:DataGrid>

As you can see from the above xaml code the columns are bound to respective properties. For UserName we have a CellEditingTemplate, where we have used an AutoCompleteBox.

Now create a class named ObjectCollection and define the two constructors as follows:

public class ObjectCollection: Collection<object>

    {

        public ObjectCollection()

        {

        }

 

        public ObjectCollection(IEnumerable collection)

        {

            foreach (object obj in collection)

            {

                Add(obj);

            }

        }

 

    }

Add a sample ObjectCollection in xaml code behind.

<UserControl.Resources>

        <local:ObjectCollection x:Key="SampleHeroes">

            <sys:String>Jack Sephered</sys:String>

            <sys:String>James Soyer</sys:String>

            <sys:String>John Lock</sys:String>

            <sys:String>Jacky Chan</sys:String>

        </local:ObjectCollection>

    </UserControl.Resources>

That's it we are done with this. Run your application.

Edit the User Name Column of any row and start typing with the letter "J" (as we have only fields starting with J).

You will be prompted with the List of values from the AutoCompleteBox:

4.gif

posted Apr 4, 2016 by Jdk

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

In this article we will explore on Pie Chart in Silverlight 3. Pie Chart comes with Silverlight 3 Toolkit.

Crating Silverlight Project

Fire up Expression Blend 3 and create a Silverlight Application. Name it as PieChartInSL3.

PieChartImg1.gif

 

Go ahead and add a Pie Series into your application.

You can find it in Asset Library.

PieChartImg2.gif

By adding a Pie Series, you just added an Assembly System.Windows.Controls.DataVisualization.

And Blend automatically refers to the Namespace.

If you see the xaml code behind you will find the following:

xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"

Now we will add some data into it.

Create a class called Appointment and add the following code into it.

public class Appointment

    {

        public int Id { get; set; }

        public string AppName { get; set; }

        public string AppointmentDetails { get; set; }

        public int Duration { get; set; }

 

        public Appointment()

        {

        }

 

        public Appointment(int id, string appName, string appointmentDetails, int duration)

        {

            Id = id;

            AppName = appName;

            AppointmentDetails = appointmentDetails;

            Duration = duration;

        }

 

    }

Pie Series takes Key Value pair as it's data. So we will create a class named AppointmentHelper which will convert a Dictionary to Key Value Pair.

 

public static Dictionary<String, int> GetTimeDistribution(this List<Appointment> appts)

        {

            Dictionary<String, int> myTimeDistribution = new Dictionary<string, int>();

 

            var appointments = (from time in appts

                                select time.AppName).Distinct();

 

            foreach (var app in appointments)

            {

                var time = (from pjts in appts

                            where pjts.AppName == app

                            select pjts.Duration).Sum();

 

                myTimeDistribution.Add(app, time);

 

            }

            return myTimeDistribution;

        }

 

Now we will add values.

List<Appointment> appointments;

 

                                public MainPage()

                                {

                                                InitializeComponent();

                CreateTimeLists();

                                }

 

        private List<AppointmentDTO> CreateTimeLists()

        {

            appointments = new List<Appointment>

            {

                new Appointment { Id=1, AppName="Meeting", AppointmentDetails="Video COnference", Duration=30},

                new Appointment { Id=1, AppName="Call", AppointmentDetails="Audio COnference", Duration=90},

                new Appointment { Id=1, AppName="Session", AppointmentDetails="Session for Silverlight", Duration=120}

            };

            return appointments;

        }

Now we will bind our data to Pie Series.

<chartingToolkit:Chart x:Name="TypicalChart" Title="Typical Pie Chart">

            <chartingToolkit:Chart.Series>

                <chartingToolkit:PieSeries Margin="0,0,20,20" d:LayoutOverrides="Width, Height" Title="Pie Chart Sample"IndependentValueBinding="{Binding Path=Key}"

                    DependentValueBinding="{Binding Path=Value}"/>

            </chartingToolkit:Chart.Series>

        </chartingToolkit:Chart>

As you see from the above code I have added two properties as IndependentValueBinding and DependentValueBinding. We need to give the Binding Path to respective key and value.

Now Type cast the chart to Pie Series and assign the ItemSource property.

private void UserControl_Loaded(object sender, RoutedEventArgs e)

        {

            ((PieSeries)TypicalChart.Series[0]).ItemsSource = appointments.GetTimeDistribution();

        }

 

Now go ahead run the application to see the Pie Chart.

PieChartImg3.gif

That's it you have successfully used Pie Series in Silverlight 3.

READ MORE

Calendar Events

Besides the normal control events, the Calendar control has three events calendar related events. These events are the DisplayDateChanged, DisplayModeChanged and SelectedDatesChanged. The DisplayDateChanged event is fired where the DisplayDate property is changed. The DisplayModeChanged event is fired when the DisplayMode property is changed. The SelectedDatesChanged event is fired when the SelectedDate or SelectedDates properties are changed. The following code snippet sets these three events attributes. 

<Calendar SelectionMode="SingleRange"  
   Name="MonthlyCalendar"   
   SelectedDatesChanged="MonthlyCalendar_SelectedDatesChanged"  
   DisplayDateChanged="MonthlyCalendar_DisplayDateChanged"  
   DisplayModeChanged="MonthlyCalendar_DisplayModeChanged"  
   HorizontalAlignment="Left"  
   VerticalAlignment="Top"  
   Margin="10,10,0,0">   
</Calendar>   

The code behind for these events look as in Listing 4. 

private void MonthlyCalendar_SelectedDatesChanged(object sender,   
    SelectionChangedEventArgs e)  
{  
}  
private void MonthlyCalendar_DisplayDateChanged(object sender,   
    CalendarDateChangedEventArgs e)  
{  
}  
private void MonthlyCalendar_DisplayModeChanged(object sender,   
    CalendarModeChangedEventArgs e)  
{  
 

Listing 4

Normally, on a date selection, you may want to capture that event and know what the current selected date is. Now how about we add a TextBox control to the page and on the date selection, we will set the text of the TextBox to the currently selected date. 

We add the following code to the XAML just below the Calendar control. <TextBox Width="200" Height="30"  
   VerticalAlignment="Bottom"  
   HorizontalAlignment="Left"  
   Margin="10,10,10,10"  
   x:Name="SelectedDateTextBox">  
</TextBox>

On the SelectedDateChanged event handler, we set the TextBox.Text property to the SelectedDate property of the Calendar control as you can see from the code in Listing 5. 

private void MonthlyCalendar_SelectedDatesChanged(object sender,   
    SelectionChangedEventArgs e)  
{  
    SelectedDateTextBox.Text = MonthlyCalendar.SelectedDate.ToString();  

Listing 5

Now when you run the application, you will see the output that looks as in Figure 10. When you select a date in the Calendar, it will be displayed in the TextBox. 


Figure 10

Formatting a Calendar


How about we create a Calendar control with a border formatting, background and foreground of the Calendar?

The BorderBrush property of the Calendar sets a brush to draw the border of a Calendar. You may use any brush to fill the border. The following code snippet uses a linear gradient brush to draw the border with a combination of the colors Red and Blue.

<Calendar.BorderBrush>  
   <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >  
      <GradientStop Color="Blue" Offset="0" />  
      <GradientStop Color="Red" Offset="1.0" />  
   </LinearGradientBrush>  
</Calendar.BorderBrush>  

The Background and Foreground properties of the Calendar set the background and foreground colors of a Calendar. You may use any brush to fill the border. The following code snippet uses linear gradient brushes to draw the background and foreground of a Calendar. 

<Calendar.Background>  
    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >  
        <GradientStop Color="Blue" Offset="0.1" />  
        <GradientStop Color="Orange" Offset="0.25" />  
        <GradientStop Color="Green" Offset="0.75" />  
        <GradientStop Color="Red" Offset="1.0" />  
    </LinearGradientBrush>  
</Calendar.Background>  
<Calendar.Foreground>  
    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >  
        <GradientStop Color="Black" Offset="0.25" />  
        <GradientStop Color="Green" Offset="1.0" />  
    </LinearGradientBrush>  
</Calendar.Foreground>  

The new Calendar looks as in Figure 11. 


Figure 11

Setting Image as Background of a Calendar


To set an image as the background of a Calendar, we can set an image as the Background of the Calendar. The following code snippet sets the background of a Calendar to an image. The code also sets the opacity of the image.

<Calendar.Background>  
   <ImageBrush ImageSource="Garden.jpg" Opacity="0.3"/>  
</Calendar.Background>  

The new output looks as in Figure 12.


Figure 12

Creating a Calendar Dynamically


The code listed in Listing 6 creates a Calendar control programmatically. First, it creates a Calendar object and sets its DisplayMode and SelectedMode and other properties and later the Calendar is added to the LayoutRoot. 

private void CreateDynamicCalendar()  
{  
    Calendar MonthlyCalendar = new Calendar();  
    MonthlyCalendar.Name = "MonthlyCalendar";  
    MonthlyCalendar.Width = 300;  
    MonthlyCalendar.Height = 400;  
    MonthlyCalendar.Background = Brushes.LightBlue;  
    MonthlyCalendar.DisplayMode = CalendarMode.Month;  
    MonthlyCalendar.SelectionMode = CalendarSelectionMode.SingleRange;  
    MonthlyCalendar.DisplayDateStart = new DateTime(2010, 3, 1);  
    MonthlyCalendar.DisplayDateEnd = new DateTime(2010, 3, 31);  
    MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 5));  
    MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 15));  
    MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 25));    
    MonthlyCalendar.FirstDayOfWeek = DayOfWeek.Monday;  
    MonthlyCalendar.IsTodayHighlighted = true;    
    LayoutRoot.Children.Add(MonthlyCalendar);  
}  

Listing 6

Summary


In this article, I discussed the calendar control using XAML and C#. We also saw how to set display modes, selection modes, blackout dates, selected dates, border, background and foreground properties. After that, we saw you to set an image as the background of a Calendar. In the end of this article, we saw how to create a Calendar dynamically.

READ MORE

   PART 2: Continuous 

 <ListBoxItem Background="LightCoral" Foreground="Red"   
             FontFamily="Verdana" FontSize="12" FontWeight="Bold">                  
        <CheckBox Name="CoffieCheckBox">  
            <StackPanel Orientation="Horizontal">  
            <Image Source="coffie.jpg" Height="30"></Image>  
            <TextBlock Text="Coffie"></TextBlock>  
        </StackPanel>  
    </CheckBox>  
</ListBoxItem>  
<ListBoxItem Background="LightGray" Foreground="Black"   
             FontFamily="Georgia" FontSize="14" FontWeight="Bold">  
    <CheckBox Name="TeaCheckBox">  
        <StackPanel Orientation="Horizontal">  
            <Image Source="tea.jpg" Height="30"></Image>  
            <TextBlock Text="Tea"></TextBlock>  
        </StackPanel>  
    </CheckBox>  
</ListBoxItem>  
<ListBoxItem Background="LightBlue" Foreground="Purple"   
             FontFamily="Verdana" FontSize="12" FontWeight="Bold">  
    <CheckBox Name="OrangeJuiceCheckBox">  
        <StackPanel Orientation="Horizontal">  
            <Image Source="OrangeJuice.jpg" Height="40"></Image>  
            <TextBlock Text="OrangeJuice"></TextBlock>  
        </StackPanel>  
    </CheckBox>  
</ListBoxItem>  
<ListBoxItem Background="LightGreen" Foreground="Green"   
             FontFamily="Georgia" FontSize="14" FontWeight="Bold">  
    <CheckBox Name="MilkCheckBox">  
        <StackPanel Orientation="Horizontal">  
            <Image Source="Milk.jpg" Height="30"></Image>  
            <TextBlock Text="Milk"></TextBlock>  
        </StackPanel>  
    </CheckBox>  
</ListBoxItem>  
<ListBoxItem Background="LightBlue" Foreground="Blue"   
             FontFamily="Verdana" FontSize="12" FontWeight="Bold">  
    <CheckBox Name="IcedTeaCheckBox">  
        <StackPanel Orientation="Horizontal">  
            <Image Source="IcedTea.jpg" Height="30"></Image>  
            <TextBlock Text="Iced Tea"></TextBlock>  
        </StackPanel>  
    </CheckBox>  
</ListBoxItem>  
<ListBoxItem Background="LightSlateGray" Foreground="Orange"  
             FontFamily="Georgia" FontSize="14" FontWeight="Bold">  
    <CheckBox Name="MangoShakeCheckBox">  
        <StackPanel Orientation="Horizontal">  
            <Image Source="MangoShake.jpg" Height="30"></Image>  
            <TextBlock Text="Mango Shake"></TextBlock>  
        </StackPanel>  
    </CheckBox>  
</ListBoxItem>  

Now, the new ListBox looks as in Figure 6.

ListBox with CheckBoxes
                                 Figure 6. ListBox with CheckBoxes

Data Binding 

Before I discuss data binding in general, I must confess, Microsoft experts have made a big mess related to data-binding in .NET 3.0 and 3.5. Instead of making things simpler, they have made them complicated. Maybe they have some bigger plans for the future but so far I have seen binding using dependency objects and properties, LINQ and DLINQ and WCF and ASP.NET Web Services and it all looks like a big mess. It's not even close to the ADO.NET model we had in .NET 1.0 and 2.0. I hope they clean up this mess in the near future.

When it comes to data binding, we need to first understand the data. Here is a list of ways a data can be consumed from:

  • Objects
  • A relational database such as SQL Server
  • A XML file
  • Other controls

Data Binding with Objects

The ItemsSource property of a ListBox binds a collection of IEnuemerable items such as an ArrayList to the ListBox control. 

// Bind ArrayList with the ListBox  
LeftListBox.ItemsSource = LoadListBoxData();  

private ArrayList LoadListBoxData()  
{  
    ArrayList itemsList = new ArrayList();  
    itemsList.Add("Coffie");  
    itemsList.Add("Tea");  
    itemsList.Add("Orange Juice");  
    itemsList.Add("Milk");  
    itemsList.Add("Mango Shake");  
    itemsList.Add("Iced Tea");  
    itemsList.Add("Soda");  
    itemsList.Add("Water");  
    return itemsList;  
}  

Sample: Transferring data from one ListBox to Another 


We've seen many requirements where a page has two ListBox controls and the left ListBox displays a list of items and using a button we can add items from the left ListBox and add them to the right side ListBoxand using the remove button we can remove items from the right side ListBox and add them back to the left side ListBox

This sample shows how to move items from one ListBox to another. The final page looks as in Figure 7. The Add button adds the selected item to the right side ListBox and removes from the left side ListBox. The Remove button removes the selected item from the right side ListBox and adds back to the left sideListBox.

ListBox
                                                                           Figure 7

add remove
                                                                           Figure 8

 

PART 4: will update soon

READ MORE

Part 2 Continous:


                   <TreeViewItem Name="Child1">  

                       <TreeViewItem.Header>  

  1.             <CheckBox Name="CoffieCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                        <Image Source="coffie.jpg" Height="30"></Image>  
                        <TextBlock Text="Coffie"></TextBlock>  
                    </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>   
        </TreeViewItem>  
        <TreeViewItem Name="Child2">  
            <TreeViewItem.Header>  
                <CheckBox Name="IcedTeaCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                        <Image Source="IcedTea.jpg" Height="30"></Image>  
                        <TextBlock Text="Iced Tea"></TextBlock>  
                    </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>  
        <TreeViewItem Name="Child3">  
            <TreeViewItem.Header>  
                <CheckBox Name="MangoShakeCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                    <Image Source="MangoShake.jpg" Height="30"></Image>  
                    <TextBlock Text="Mango Shake"></TextBlock>  
                </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>  
        <TreeViewItem Name="Child4">  
            <TreeViewItem.Header>  
                <CheckBox Name="MilkCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                    <Image Source="Milk.jpg" Height="30"></Image>  
                    <TextBlock Text="Milk"></TextBlock>  
                </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>  
        <TreeViewItem Name="Child5">  
            <TreeViewItem.Header>  
                <CheckBox Name="TeaCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                    <Image Source="Tea.jpg" Height="30"></Image>  
                    <TextBlock Text="Tea"></TextBlock>  
                </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>  
        <TreeViewItem Name="Child6">  
            <TreeViewItem.Header>  
                <CheckBox Name="OrangeJuiceCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                    <Image Source="OrangeJuice.jpg" Height="30"></Image>  
                    <TextBlock Text="Orange Juice"></TextBlock>  
                </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>                  
    </TreeViewItem>  

The new TreeView looks as in the following:

TreeView with CheckBoxes
                                    Figure 6. TreeView with CheckBoxes

Before I discuss data binding in general, I must confess, the Microsoft experts have made a big mess related to data-binding in .NET 3.0 and 3.5. Instead of making things simpler, they have made them complicated. Maybe they have bigger plans in the future, but so far I have seen binding using dependency objects and properties, LINQDLINQWCF and ASP.NET Web Services and it all looks like a big mess. It's not even close to the ADO.NET model we had in .NET 1.0 and 2.0. I hope they solve this problem in the near future.

When it comes to data binding, we need to first understand the data. Here is a list of the ways data can be consumed: 

  • Objects
  • A relational database such as SQL Server
  • A XML file or
  • Other controls

The ItemsSource property of a TreeView is used to bind a collection of IEnuemerables such as anArrayList to the TreeView control. 

  1. // Bind ArrayList with the TreeView  
    LeftTreeView.ItemsSource = LoadTreeViewData();              
      
    private ArrayList LoadTreeViewData()  
    {  
        ArrayList itemsList = new ArrayList();  
        itemsList.Add("Coffie");  
        itemsList.Add("Tea");  
        itemsList.Add("Orange Juice");  
        itemsList.Add("Milk");  
        itemsList.Add("Mango Shake");  
        itemsList.Add("Iced Tea");  
        itemsList.Add("Soda");  
        itemsList.Add("Water");  
        return itemsList;  
    }  


Note:  Part 4 will update soon.  

READ MORE

Its important that when you think in terms of Silverlight controls, you always think in terms of XAML and that means thinking in terms of a Visual Tree.  Elements in the tree have parents and elements in the tree have children.  A popup control is no  different. Although it appears to look like this disassociated control floating around, it really is just another element in the Visual Tree (Unbeknownst to the naked eye).

In order to position a popup relative to an existing control, you should make it a child of the control.   If the control does not allow children, then put the control in a Grid and you can have all the children you want.  Here is an example.
 

  private void OnHoverTab(object sender, MouseEventArgs e)

  {

  var p = new Popup();

  p.DataContext = ((sender as FrameworkElement).Parent as  
            FrameworkElement).DataContext;

  p.Child = new UnderlyingUserControl();  // puts a user control in the popup

  p.VerticalOffset = 25; // this will offset us slightly from the
                          // parent

  p.HorizontalOffset = 0;

  p.IsOpen = true;

   // this is where we add the popup to a Grid we can position
   // against

  ((sender as FrameworkElement).Parent as Grid).Children.Add(p);

  }



Now once we dismiss our popup, it's important to remove it from the Grid, otherwise we'll end up with lots and lots of dead popups in our Grid tree.

I've added an OK and Cancel onto my Underlying user control to dismiss the popup, here is the code behind for the Child of the popup:
 

  private void OnOK(object sender, RoutedEventArgs e)

    {

      ((MyViewModel) DataContext).Name = NameInput.Text;

// Hide the popup and remove from the parent

      (this.Parent as Popup).IsOpen = false;

      ((this.Parent as Popup).Parent as  Grid).Children.Remove(this.Parent asPopup);

    }

 

    private void OnCancel(object sender, RoutedEventArgs e)

    {

    // Hide the popup and remove from the parent

      (this.Parent as Popup).IsOpen = false;

      ((this.Parent as Popup).Parent as Grid).Children.Remove(this.Parent as Popup);

    }

 

READ MORE

Introduction

If you are developing a Silverlight Application, and you need to pass some parameters inside – for example a key and value pair then we can pass the key value pair from the aspx page itself. We will see how we can do this in Silverlight.

Create a Silverlight Project



Figure 1.1 Creating Silverlight Project

Adding parameters

Open the "InitializingParametersTestPage.aspx" and find the tag tag  <asp:Silverlight  add an attribute InitParameters
Enter the following code to the tag

InitParameters="Key1=Value1,Key2=Value2"

Defining the Parameters

In App.xaml.cs add an object of IDictionary<string,string> as follows

public IDictionary<string, string> AppParams;
In Application_Startup event initialize the parameters as follows
private void Application_Startup(object sender, StartupEventArgs e)
        {
            AppParams = e.InitParams;
            this.RootVisual = new Page();
        }

Using Parameters

In Page.xaml add ListBoxes to show the parameter values
Xaml Code

<UserControl x:Class="InitializingParameters.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="#FFB7C2E5">
                <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="0.472*"/>
                                <ColumnDefinition Width="0.025*"/>
                                <ColumnDefinition Width="0.502*"/>
                </Grid.ColumnDefinitions>
        <ListBox x:Name="myKeysList"/>
        <ListBox x:Name="myValuesList" Grid.Column="2"/>
    </Grid>
</UserControl>

In code behind of the Page.xaml.cs add the following code to bind the parameters

namespace InitializingParameters
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
            App myApp = App.Current as App;

            foreach (string item in myApp.AppParams.Keys)
            {
                myKeysList.Items.Add(item);
            }
            foreach (string item1 in myApp.AppParams.Values)
            {
                myValuesList.Items.Add(item1);
            }
        }
    }
}

Runnning the Application

When you run the application the list will carry the key and value pairs.



Figure 1.2 Displaying Key Value pair

READ MORE
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...