【发布时间】:2013-04-26 12:49:54
【问题描述】:
我正在尝试从用户控件访问父窗口。
userControl1 uc1 = new userControl1();
mainGrid.Children.Add(uc1);
通过此代码,我将userControl1 加载到主网格。
但是当我点击userControl1 中的一个按钮时,我想将另一个userControl2 加载到主窗口中的mainGrid 中?
【问题讨论】:
我正在尝试从用户控件访问父窗口。
userControl1 uc1 = new userControl1();
mainGrid.Children.Add(uc1);
通过此代码,我将userControl1 加载到主网格。
但是当我点击userControl1 中的一个按钮时,我想将另一个userControl2 加载到主窗口中的mainGrid 中?
【问题讨论】:
你试过了吗
Window yourParentWindow = Window.GetWindow(userControl1);
【讨论】:
这将获得根级窗口:
Window parentWindow = Application.Current.MainWindow
或直接父窗口
Window parentWindow = Window.GetWindow(this);
【讨论】:
建议的唯一原因
Window yourParentWindow = Window.GetWindow(userControl1);
对你没用是因为你没有把它转换成正确的类型:
var win = Window.GetWindow(this) as MyCustomWindowType;
if (win != null) {
win.DoMyCustomWhatEver()
} else {
ReportError("Tough luck, this control works only in descendants of MyCustomWindowType");
}
除非您的窗口类型和控件之间必须更多地耦合,否则我认为您的方法设计不佳。
我建议将控件将在其上运行的网格作为构造函数参数传递,将其设置为属性或在任何Window 内动态搜索适当的(根?)网格。
【讨论】:
修改 UserControl 的构造函数以接受 MainWindow 对象的参数。然后在 MainWindow 中创建时将 MainWindow 对象传递给 UserControl。
主窗口
public MainWindow(){
InitializeComponent();
userControl1 uc1 = new userControl1(this);
}
用户控制
MainWindow mw;
public userControl1(MainWindow recievedWindow){
mw = recievedWindow;
}
用户控件中的示例事件
private void Button_Click(object sender, RoutedEventArgs e)
{
mw.mainGrid.Children.Add(this);
}
【讨论】:
谢谢你们帮助我。我有另一个解决方案
((this.Parent) as Window).Content = new userControl2();
这是完美的工作
【讨论】:
制作一个主窗口的静态实例,你可以简单地在你的用户控件中调用它:
看这个例子:
Window1.cs
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
_Window1 = this;
}
public static Window1 _Window1 = new Window1();
}
UserControl1.CS
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void AddControl()
{
Window1._Window1.MainGrid.Children.Add(usercontrol2)
}
}
【讨论】: