使按钮的事件处理程序单击以启动一个名为MainPage_Loaded的新事件

|| 因此,目前,我的页面当前正在使用CS文件中的以下代码。我需要更改的是添加一个事件处理程序,以便单击按钮时,MainPage_Loaded仅在单击此按钮之后发生。 我知道那条线
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
当前正在调用此方法以启动,但是当我尝试将此代码放入button1_click事件处理程序时,它不起作用。
  public MainPage()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(MainPage_Loaded);     
    }

    public void button1_Click(object sender, RoutedEventArgs e)
    {


    }

    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        var ctx = new HazchemEntities(new Uri(\"http://devweb.compsci.chester.ac.uk/0808092/CO6009/HazchemService.svc/\"));
        App.coll = new DataServiceCollection<tblChemical>(ctx);
        Lst.ItemsSource = App.coll;

        App.coll.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(coll_LoadCompleted);

        var qry = \"/tblChemicals?$filter UNNumber = eq\'\" + Search.Text + \"\'\";
        App.coll.LoadAsync(new Uri(qry, UriKind.Relative));

        if (!App.ViewModel.IsDataLoaded)
        {
            App.ViewModel.LoadData();
        }


   }
这是我正在使用的XAML代码。
    <StackPanel x:Name=\"TitlePanel\" Grid.Row=\"0\" Margin=\"12,17,0,28\">
        <TextBlock x:Name=\"ApplicationTitle\" Text=\"MY APPLICATION\" Style=\"{StaticResource PhoneTextNormalStyle}\"/>
        <TextBlock x:Name=\"PageTitle\" Text=\"page name\" Margin=\"9,-7,0,0\" Style=\"{StaticResource PhoneTextTitle1Style}\"/>
        <TextBox x:Name=\"Search\"  Height=\"72\" Margin=\"-4,0,50,0\" Text=\"TextBox\" VerticalAlignment=\"Top\" Width=\"350\" HorizontalAlignment=\"Left\"/>
        <Button Content=\"Go\" Height=\"72\" HorizontalAlignment=\"Left\" Margin=\"350,0,0,0\" Name=\"button1\" VerticalAlignment=\"Top\" Width=\"100\" Click=\"button1_Click\" />

    </StackPanel>
仅在单击此按钮时,我需要在button1_Click事件中添加什么以使其开始加载mainpage_load? 谢谢     
已邀请:
您似乎误解了一些东西……这行:   已加载+ = new RoutedEventHandler(MainPage_Loaded); 不会导致立即调用
void MainPage_Loaded(object sender, RoutedEventArgs e)
函数。它正在为该事件注册一个处理程序-当MainPage完成加载后,它将在内部触发Loaded事件,进而调用该事件处理程序。 在
button1_Click
中设置该处理程序也没有意义-在单击按钮时,您的页面已经正确加载。 如果您希望
button1_Click
也使用
MainPage_Loaded
函数中的某些功能,则应将其重构为一个单独的函数,它们都可以调用。     
您正在将EventHandler分配给MainPage Loaded事件,而不是单击按钮。 在构造函数中,尝试
this.button1.OnClick += new RoutedEventHandler(MainPage_Loaded);
    
将以下代码添加到button1_Click
MainPage_Loaded(sender,e);
    

要回复问题请先登录注册