2017-12-07 17 views
0

주 창이 있습니다. 메인 윈도우에서 Usercontrols를 호출합니다. mainwindow.loaded 섹션에서 Usercontrol1을 호출합니다. Usercontrol1 대신 Usercontrol1 단추를 클릭하여 Usercontrol2를 가져오고 싶습니다.WPF 사용자 컨트롤 호출자가 작동하지 않습니다.

내 UserControl을 발신자 클래스 :

public class uc_call 
{ 
    public static void uc_add(Grid grd, UserControl uc) 
    { 
     if (grd.Children.Count > 0) 
     { 
      grd.Children.Clear(); 
      grd.Children.Add(uc); 
     } 
     else 
     { 
      grd.Children.Add(uc); 
     } 
    } 
} 

내 Mainwindow_Loaded (그것은 작동) : UserControl1을에

uc_call.uc_add(Content, new UserControl1()); 

버튼 클릭 기능 :

 MainWindow mw = new MainWindow(); 
     uc_call.uc_add(mw.Content, new Usercontrol2()); 

답변

1

새로운 MainWindow를 생성하지 마십시오. 대신, 기존 하나를 사용하다

var topLevelPanel = Application.Current.MainWindow.Content as Panel; 

if (topLevelPanel != null) 
{ 
    topLevelPanel.Children.Clear(); 
    topLevelPanel.Children.Add(new Usercontrol2()); 
} 

참고 컬렉션이 비어있는 경우에도 Children.Clear() 전화를 다치게하지 않습니다.

var mainWindow = (MainWindow)Application.Current.MainWindow; 
var grid = mainWindow.Content; 
grid.Children.Clear(); 
grid.Children.Add(new Usercontrol2()); 

또는 정적 방법 : 내가 원하는

var mw = (MainWindow)Application.Current.MainWindow; 
uc_call.uc_add(mw.Content, new Usercontrol2()); 
+0

경우

당신은 자식 요소를 교체하려는 그리드를 보유하고 다른 Content 속성을 추가 한 사용자가 Mainwindow 내부의 그리드에서 변경하도록 제어합니다. 내가하는 말을하면, 메인 윈도우 안의 모든 객체가 사라집니다. 메인 윈도우의 객체를 유지하려면 어떻게해야합니까? –

+0

내 desing 및 usercontrol1 : https://ibb.co/fkOcVG - usercontrol1을 바꾸려면 usercontrol1을 원하지만 버튼을 클릭하십시오. https://ibb.co/npb9cw –

+0

여기에 'topLevelPanel'이 최상위 레벨 그리드입니다. MainWindow의 Content (즉,'mw.Content') 속성에 할당됩니다. 아니면 다른 'Content' 필드 또는 속성을 추가 했습니까? – Clemens