Saturday, May 19, 2012

Access Child window data in parent window

  1. Create a new Silverlight Application.
  2. Right-click on the project and select Add New Item.
  3. Select Silverlight Child Window template from the Add New Item dialog and give name to childwindow as ChildWindowForm
  4. In ChildWindowForm.xaml add a textbox whose value we will pass back to the parent window(MainPage.xaml)
<TextBox Name=" txtChildWindowTextBox" />
    5.   In ChildWindowForm.xaml.cs
Create public property to save the value
it is possible to access the value of the TextBox control we added in the Child Window directly from the MainPage.xaml.cs, however, this is a terrible practice as it will reduces  code stability in the future. Therefore create a public property of type string to save the value of TextBox control.
private string _dataFromChildWindow;

public string DataFromChildWindow
get { return _dataFromChildWindow; }
set { _dataFromChildWindow = value; }

Create an EventHandler in Child Window
public event EventHandler SubmitClicked;
Fire the event once submit button is clicked in Child Window
there should already be a method for when the OK (Submit) button is pressed, it is called OKButton_Click. Inside that we need to fire the event which we created earlier, so that our event gets fired when the code reaches this method i.e. when we press OK in Child Window.
private void OKButton_Click(object sender, RoutedEventArgs e)
            if (SubmitClicked != null)
                _dataFromChildWindow = txtChildWindowTextBox.Text;
                SubmitClicked(this, new EventArgs());
            this.DialogResult = true;

6. In ParentWindow.xaml
In ParentWindow.xaml we will add a textbox txtChildWindowData which will display data entered in Child Window(ChildWindowForm)

<TextBlock Text="Data From Child Window : " Margin="12,84,229,193" />
        <TextBlock Height="23" HorizontalAlignment="Right" Margin="0,84,50,0" Name="txtChildWindowData" Text="Not Set" VerticalAlignment="Top" Width="155" />
        <Button Content="Show Child Window" Height="23" HorizontalAlignment="Left" Margin="126,169,0,0" Name="btnShowChildWindow" VerticalAlignment="Top" Width="144" Click="btnShowChildWindow_Click" />

btnShowChildWindow_Click we will show childwindow and write a event which will get fired from childwindow  when user clicks OK button.
In this event we will read/get the data set in child window property.

  private void btnShowChildWindow_Click(object sender, RoutedEventArgs e)
            ChildWindowForm objChildWindow = new ChildWindowForm();
            objChildWindow.SubmitClicked += new EventHandler(objChildWindow_SubmitClicked);

  void objChildWindow_SubmitClicked(object sender, EventArgs e)
            txtChildWindowData.Text = (sender as ChildWindowForm).DataFromChildWindow;


I Hope this helps...

No comments:

Post a Comment