加载时加载额外的 window、运行 代码

Load additional window, run code when it's loaded

我正在尝试打开一个新的 window,打开后我想 运行 更多代码来填充 TreeView。我想通过命令执行此操作,因此我不需要在 window 后面添加任何代码。

这是我的命令:

类 > 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");
        }
    }
}

有2个问题:

1) 您的 LoadFolderTree 函数签名错误:没有参数而不是事件处理程序 sender/Eventargs 的典型参数

2) 你需要一个函数对象来调用非静态方法

可能的修复:

1) 使函数静态化并添加正确的参数

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

2) 从 Functions 的实例调用函数并添加正确的参数

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");
    }