2015-10-16 73 views
0

我想打開一個新窗口,當它打開時,我想運行更多代碼來填充TreeView。我想從命令中做到這一點,所以我不需要在窗口後面添加任何代碼。加載其他窗口,加載時運行代碼

這裏是我的命令:

類> Commands.cs

 /// <summary> 
     /// Command: SelectFolder 
     /// </summary> 
     #region SelectFolder 
     public static RoutedUICommand SelectFolder 
     { 
      get { return _SelectFolder; } 
     } 
     public static void SelectFolder_Executed(object sender, 
        ExecutedRoutedEventArgs e) 
     { 
      Window FolderDialog = new Views.FolderExplorer(); 
      FolderDialog.Show(); 

      //Bind Commands 
      Classes.MyCommands.BindCommandsToWindow(FolderDialog); 

      FolderDialog.ContentRendered += Functions.LoadFolderTree(); 
     } 
     public static void SelectFolder_CanExecute(object sender, 
          CanExecuteRoutedEventArgs e) 
     { 
      e.CanExecute = true; 
     } 
     #endregion 

收到此錯誤:

Cannot implicitly convert type 'void' to 'System.EventHandler'

An object reference is required for the non-static field, method, or property 'Functions.LoadFolderTree()'

目前,我試圖運行一個函數然後會填充TreeView,但是如果有一個很好的方法可以從Command中執行,而不需要額外的功能,那麼請說。這是我當前的代碼:

類> Functions.cs

namespace Duplicate_Deleter.Classes 
{ 
    class Functions 
    { 
     public void LoadFolderTree() 
     { 
      MessageBox.Show("Hello"); 
     } 
    } 
} 

回答

1

有2個問題:

1)您LoadFolderTree功能的簽名錯誤:沒有參數,而不是事件處理程序的典型sender/Eventargs參數

2)您需要一個Function對象來調用非靜態方法

可能的修正:

1)使函數靜態並添加正確的參數

public class Functions 
{ 
    public static void LoadFolderTree(object sender, EventArgs eventArgs) 
    { 
     MessageBox.Show("Hello"); 
    } 
} 

2)請從函數的一個實例功能,並添加正確的參數

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 

     var f = new Functions(); 
     ContentRendered += f.LoadFolderTree; 
    } 
} 

public class Functions 
{ 
    public void LoadFolderTree(object sender, EventArgs eventArgs) 
    { 
     MessageBox.Show("Hello"); 
    } 
} 

3)最好的方法:只需添加默認的事件處理程序。輸入「ContentendRendered + =」,然後按兩次「tab」自動添加正確的事件處理程序

public MainWindow() 
    { 
     InitializeComponent(); 
     ContentRendered += MainWindow_ContentRendered; 
    } 

    void MainWindow_ContentRendered(object sender, EventArgs e) 
    { 
     MessageBox.Show("Hello"); 
    }