【发布时间】:2016-09-28 09:13:02
【问题描述】:
我在 wpf 中有两个用户控件,并且我在它们两个中都定义了简单的子窗口现在我想以 Uc1 有 child1 和 Uc2 有 child2 的方式访问它们我想从 Uc1 访问 child2,反之亦然从代码后面。
【问题讨论】:
我在 wpf 中有两个用户控件,并且我在它们两个中都定义了简单的子窗口现在我想以 Uc1 有 child1 和 Uc2 有 child2 的方式访问它们我想从 Uc1 访问 child2,反之亦然从代码后面。
【问题讨论】:
我这样做的方式是通过主窗口。您不想在两个控件之间创建依赖关系。这是因为重用了用户控件。
这是一个通过事件传递孩子的示例。我不会将主窗口作为引用传递给 UserControl 的构造函数。
如果你想这样做,你应该创建一个接口并在 MainWindow 上实现它并将它作为接口传递。
喜欢:
UC1-(event)>MainWindow-(methodcall)>UC2-(methodcall)>UC2.child
伪代码:
// event args.
public class RequestChildEventArgs : EventArgs
{
public Child2 Child { get;set; }
}
public class UC1
{
// do something when you need the child2
public void DoSomething()
{
var child2 = GetChild2();
if(child2 == null)
// cry.
}
// this method requests a reference of child2
private Child2 GetChild2()
{
// check if the event is assigned.
if(RequestChild == null)
return null;
RequestChildEventArgs args = new RequestChildEventArgs();
RequestChild2(this, args);
return args.Child;
}
public event EventHandler<RequestChildEventArgs> RequestChild2;
}
// user control 2
public class UC2
{
public Child2 Child2 { get; } = new Child2();
}
// the mainwindow that tunnels the Child2
public class MainWindow
{
private UC1 _uc1;
private UC2 _uc2;
public MainWindow()
{
_uc1 = new UC1();
_uc2 = new UC2();
_uc1.RequestChild2 += (s, e) => e.Child = _uc2.Child2;
}
}
反之亦然:
伪代码:
// event args.
public class RequestChildEventArgs<T> : EventArgs
{
public T Child { get; set; }
}
public class UC1
{
public Child1 Child1 { get; } = new Child1();
// do something when you need the child2
public void DoSomething()
{
var child2 = GetChild2();
if (child2 == null)
// cry.
}
// this method requests a reference of child2
private Child2 GetChild2()
{
// check if the event is assigned.
if(RequestChild2 == null)
return null;
RequestChildEventArgs<Child2> args = new RequestChildEventArgs<Child2>();
RequestChild2(this, args);
return args.Child;
}
public event EventHandler<RequestChildEventArgs<Child2>> RequestChild2;
}
// user control 2
public class UC2
{
public Child2 Child2 { get; } = new Child2();
// do something when you need the child1
public void DoSomething()
{
var child1 = GetChild1();
if(child1 == null)
// cry.
}
// this method requests a reference of child1
private Child1 GetChild1()
{
// check if the event is assigned.
if(RequestChild1 == null)
return null;
RequestChildEventArgs<Child1> args = new RequestChildEventArgs<Child1>();
RequestChild1(this, args);
return args.Child;
}
public event EventHandler<RequestChildEventArgs<Child1>> RequestChild1;
}
// the mainwindow that tunnels the Childs
public class MainWindow
{
private UC1 _uc1;
private UC2 _uc2;
public MainWindow()
{
_uc1 = new UC1();
_uc2 = new UC2();
_uc1.RequestChild2 += (s, e) => e.Child = _uc2.Child2;
_uc2.RequestChild1 += (s, e) => e.Child = _uc1.Child1;
}
}
这样你的用户控件不依赖于主窗口或单例对象。
【讨论】: