Silverlight Child Window - Passing Data Between Child And Parent



Create a Silverlight Project named SLChildControl.

Add a ChildWindow Control as shown in the figure:

Silverlight application

A childWindow Control gets added as shown below:

add Silverlight Child Window

Add the following code to MyChildWindow.xaml.cs

      public const string InputPropertyName = "Input";
      public string Input
      {
         get
         {
             return (string)GetValue(InputProperty);
         }
         set
         {
             SetValue(InputProperty, value);
         }
      }
     
      public
static readonly DependencyProperty InputProperty
      = DependencyProperty.Register(
      InputPropertyName,typeof(string),typeof(MyChildWindow),new PropertyMetadata("Enter text..."));

Now modify the MainPage.xaml as shown below:

    <Grid x:Name="LayoutRoot" Background="White">
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="136,124,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="120,36,0,0" Name="InputTextBlock" VerticalAlignment="Top" Width="120" />
    </
Grid>

Modify the Code Behind as follows:

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            var window = new MyChildWindow();
            window.Closed += new EventHandler(window_Closed);
            window.Show();
        }
        void window_Closed(object sender, EventArgs e)
        {
            var window = sender as MyChildWindow;
            if (window != null && window.DialogResult == true)
            {
                InputTextBlock.Text = window.Input;
            }
        }

Let's give it a run:

run Silverlight application

Hit the Button. The child window should open.

Silverlight Child Window

Hit OK.

Child Window in silverlight

The TextBox in the MainPage gets updated with the text "Enter text ….".

How this works is, well, when you hit the ok or close button on the child, the child close event is called and it assigns the text to the textbox of the MainPage.

Silverlight Child Window
  

Up Next
    Ebook Download
    View all
    Learn
    View all