2017-12-07 19 views
0

私はメインウィンドウを持っています。私はメインウィンドウのUsercontrolsを呼び出します。私はmaincontroller.loadedセクションでUsercontrol1を呼び出します。 Usercontrol1の代わりにUsercontrol1のボタンをクリックして、Usercontrol2を持っていきたいと思います。WPFユーザーコントロールの呼び出し元が動作しません

マイユーザーコントロールの呼び出し元クラス:

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

新しいメインウィンドウを作成しないでください。コレクションが空の場合でもChildren.Clear()を呼び出すために悪くはないされて

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

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

注:代わりに、既存のものを使用します。私が欲しい

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

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

またはあなたの静的メソッドを持つ:あなたは子要素を置き換えたいグリッドを保持している別のContentプロパティを追加した場合


ユーザーはMainwindow内のグリッド上で変更するように制御します。あなたが言うことをすると、メインウィンドウ内のすべてのオブジェクトが失われます。メインウィンドウのオブジェクトを残すにはどうすればいいですか? –

+0

私のdesingとusercontrol1:https://ibb.co/fkOcVG - 私はusercontrol1を置き換えるが、ボタンをクリックするとusercontrol2にします:https://ibb.co/npb9cw –

+0

ここでは 'topLevelPanel'はトップレベルのグリッドです。 MainWindowのContent(つまり、 'mw.Content')プロパティに割り当てられています。あるいは、別の 'Content'フィールドやプロパティを追加しましたか? – Clemens

関連する問題