原文:http://blog.csdn.net/kiss0622/article/details/5852153
方法一:
1.父窗口代码
Window1.xaml.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
Window2 w2 = new Window2(this.Top, this.Left);//this.Top,this.Left 作用是将当前父窗体的位置传给子窗体 if (w2.ShowDialog()==true)
{
text1.Text = w2.name;
}
}
}
2.子窗口代码
Window2.xaml.cs
public string name;
public Window2(double x,double y)
{
InitializeComponent();
//启用‘Manual’属性后,可以手动设置窗体的显示位置
this.WindowStartupLocation = WindowStartupLocation.Manual;
this.Top = x;
this.Left = y;
//如需手动绑定事件,如下
this.but1.AddHandler(Button.ClickEvent,new RoutedEventHandler(OkButton_Click));
} private void but1_Click(object sender, RoutedEventArgs e)
{
name = "hlr";
this.DialogResult = true;//必须设置,否则无法回传
}
如果使用MVVM,当前按钮有command事件,并且command中有判断条件,这里应该相应的做修改,示例如下:
选中DataGrid某行,才允许继续往下执行,即执行父窗口的if (w2.ShowDialog()==true){}内的代码,否则,没选中也执行
var item = this.DataGrid.SelectedItem;
if (item != null)
{
this.DialogResult = true;
}
方法二:使用事件(MVVM下)
场景:通过命令,调出查询窗口,将选中项数据传回
父窗口的VM
#region 信息检索命令
private RelayCommand _SearchCommand; public RelayCommand SearchCommand
{
get
{
return _SearchCommand
?? (_SearchCommand = new RelayCommand(ExecuteSearchCommand));
}
} /// <summary>
/// 检索命令逻辑
/// </summary>
/// <param name="obj"></param>
private void ExecuteSearchCommand(object obj)//object obj
{
AddDialog v = new AddDialog();
v.Closed += v_Closed;
v.ShowDialog();
}
private void v_Closed(object sender, EventArgs e)
{
var frm = (AddDialog)sender;
var item = (ModelAdd)frm.DataGrid.SelectedItem;
if (item != null)
{
var id = item.ID;
}
}
#endregion
存在的隐患:
只要窗口关闭,都会执行v_Closed
场景示例:选中DataGrid某行,点击确认按钮,确认事件中通过一定的判断规则,符合条件则执行v_Closed
可能隐患:用户选中DataGrid某行,但是点击了取消按钮,并无验证“确认事件”中的判断规则,执行v_Closed导致出错
解决:设置共有变量进行状态控制;在v_Closed中设置相应的判断(不推荐,如产生变更可能因忘记修改导致不同步,除非是特简单的条件);