简体   繁体   English

如何从另一个 void c# 获得 object

[英]How do I get an object from another void c#

I want to change item.header from the Timer_Elapsed method.我想从Timer_Elapsed方法更改item.header How can I acheive it?我怎样才能实现它? This is my code:这是我的代码:

namespace Oceansurfer
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 5000;
            timer.AutoReset = true;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }

        public void TabView_Loaded(object sender, RoutedEventArgs e)
        {
            TabViewItem item = CreateNewTab(1);
            item.Header = Shared.FileHelper.ReadTitleFromFile();
            (sender as TabView).TabItems.Add(item);
        }
        public void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {    
        }
    }
}

Please, if you can answer this, I will be very grateful.请,如果你能回答这个问题,我将非常感激。

You can define a private member, in this case, all methods of the current class to access this item or you can use the TabItems of TabView to get the latest item.您可以定义一个私有成员,在这种情况下,当前 class 的所有方法都可以访问该项目,也可以使用 TabView 的 TabItems 获取最新项目。 In addition, if you want to change the Header of TabeViewItem in Timer_Elapsed method, since the timer is used with worker threads and the UI needs to be updated in the UI thread, you need to use Dispatcher.RunAsync method to back to the UI thread.另外,如果要在Timer_Elapsed方法中改变TubeViewItem的Header,由于定时器是配合工作线程使用的,UI需要在UI线程中更新,所以需要使用Dispatcher.RunAsync方法回到UI线程.

private TabViewItem currentItem;

public async void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        //TabViewItem item = Tabs.TabItems[Tabs.TabItems.Count-1] as TabViewItem;
        currentItem.Header = "hello2";
    });

}

private void Tabs_Loaded(object sender, RoutedEventArgs e)
{
    TabViewItem item = CreateNewTab(1);
    item.Header = Shared.FileHelper.ReadTitleFromFile();
    (sender as TabView).TabItems.Add(item);
    currentItem = item;
}

You cannot access the local variables of one method from within another method.您不能从另一种方法中访问一种方法的局部变量。 However, there are multiple ways to access the same object in different methods.但是,有多种方法可以通过不同的方法访问同一个 object。 The procedural way would be to return it as the result of one method and/or pass it as a parameter to another method.程序方式是将其作为一种方法的结果返回和/或将其作为参数传递给另一种方法。 The object oriented (and recommended) way is, when the methods are all part of the same class, make a field (or property) for the object you want to access in multiple methods. object 面向(和推荐)的方式是,当方法都是同一个 class 的一部分时,为要在多个方法中访问的 object 创建一个字段(或属性)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM