0
我在wpf中有兩個用戶控件,並且我已經在它們中定義了簡單的子窗口現在我想以像Uc1的方式訪問它們有child1和Uc2有child2我想訪問child2來自Uc1,反之亦然。如何從其他UserControl訪問SimpleChildWindow
我在wpf中有兩個用戶控件,並且我已經在它們中定義了簡單的子窗口現在我想以像Uc1的方式訪問它們有child1和Uc2有child2我想訪問child2來自Uc1,反之亦然。如何從其他UserControl訪問SimpleChildWindow
我會這樣做的方式是通過主窗口。您不想在兩個控件之間創建依賴關係。這是因爲重用了usercontrols。
這是一個通過一個事件傳遞孩子的例子。我不會將主窗口作爲UserControl的構造函數的參考。
如果你想這樣做,你應該創建一個接口並在MainWindow上實現它並將它作爲接口傳遞。
像:
UC1-(event)>
主窗口-(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;
}
}
這種方式是你用戶控件不 dependend在主窗口或單一對象。
可以請你在這裏發佈代碼?這對我來說真的很有幫助! –
非常感謝你!它會爲我工作! –