Skip to main content
 首页 » 编程设计

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

2024年02月23日14lonelyxmas

所以目前我的页面正在使用我的 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_loaded?

谢谢

请您参考如下方法:

你好像误会了什么……这一行:

this.Loaded += new RoutedEventHandler(MainPage_Loaded);

不会导致立即调用 void MainPage_Loaded(object sender, RoutedEventArgs e) 函数。它正在为该事件注册一个处理程序 - 当 MainPage 完成加载时,它会在内部触发 Loaded 事件,进而调用事件处理程序。

在 button1_Click 中设置该处理程序也没有任何意义 - 您的页面在可以单击按钮时已经正确加载。

如果您希望 button1_Click 也使用 MainPage_Loaded 函数中的某些功能,那么您应该将其重构为一个它们都可以调用的单独函数。