silverlight 对ChildWindow返回给父窗体值的理解
这篇文章是我对ChildWindow的理解,举例说明:
有时候在项目中需要弹出子窗体进行一些操作,然后将操作的值返回到父窗体中。
下图是子窗体的界面(比较粗糙。。。。)
下面贴出其代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <controls:ChildWindow x:Class="FineMmarketing.Controls.SelectChild" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls" 5 Width="365" Height="226" 6 Title="请选择纬度"> 7 <Grid x:Name="LayoutRoot" Margin="2" > 8 <Grid.RowDefinitions> 9 <RowDefinition /> 10 <RowDefinition Height="Auto" /> 11 </Grid.RowDefinitions> 12 <StackPanel Margin="0,0,0,37"> 13 <TextBlock Width="100" Height="30" Text="请输入纬度:" Margin="83 35 0 0" HorizontalAlignment="Left" /> 14 <TextBox x:Name="Txt" Width="200" Height="30" HorizontalAlignment="Center" Margin="24 0 0 0"/> 15 </StackPanel> 16 17 <Button x:Name="CancelButton" Content="取消" Click="CancelButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,0,0" Grid.Row="1" /> 18 <Button x:Name="OKButton" Content="确定" Click="OKButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,79,0" Grid.Row="1" /> 19 </Grid> 20 </controls:ChildWindow>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary> 2 /// 确定按钮 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void OKButton_Click(object sender, RoutedEventArgs e) 7 { 8 if (!String.IsNullOrEmpty(this.Txt.Text)) 9 { 10 Regex reg = new Regex("^[0-9]+$"); 11 Match ma = reg.Match(this.Txt.Text.ToString()); 12 if (ma.Success) 13 { 14 Num = Convert.ToInt32(this.Txt.Text.ToString()); 15 if (Num > 10) 16 { 17 MessageBox.Show("纬度不能超过10!"); 18 return; 19 } 20 else 21 { 22 this.Tag = Num; 23 } 24 } 25 else 26 { 27 MessageBox.Show("请输入正确的纬度!"); 28 } 29 } 30 else 31 { 32 MessageBox.Show("请输入纬度!"); 33 } 34 this.DialogResult = true; 35 } 36 /// <summary> 37 /// 取消按钮 38 /// </summary> 39 /// <param name="sender"></param> 40 /// <param name="e"></param> 41 private void CancelButton_Click(object sender, RoutedEventArgs e) 42 { 43 this.DialogResult = false; 44 }
然后看一下在父窗体中如何调用子窗体,然后后台定义事件执行子窗体关闭事件。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 SelectChild myChild = new SelectChild();//申明子窗体对象 2 ////定义子窗体关闭事件 3 myChild.Closed += new EventHandler(win_Closed); 4 5 6 /// <summary> 7 /// 子窗口关闭返回值事件 8 /// </summary> 9 /// <param name="sender"></param> 10 /// <param name="e"></param> 11 void win_Closed(object sender,EventArgs e) 12 { 13 bool? result = myChild.DialogResult; 14 //判断是否是顶级确定按钮关闭并且有返回值 15 if (result.HasValue && result.Value) 16 { 17 //是定义在子窗体中的公有的全局变量 18 MessageBox.Show(myChild.txt); 19 } 20 }