尝试从另一个线程访问SelectedIndex

时间:2016-09-21 13:45:31

标签: c# .net wpf

我需要从另一个帖子访问SelectedIndex的{​​{1}}属性,我尝试使用这样的TabControl

Dispatcher

但我得到

  

System.InvalidOperationException

     

无法通过调用线程访问该对象,因为该对象归另一个线程属性所有。

我正在尝试通过public ListView CurrentTab { get { ListView listView = null; Action action = () => { int currentTab = MainWindow.AppWindow.TabControl.SelectedIndex; //Check wich tab is opened switch (currentTab) { case 0: listView = MainWindow.AppWindow.PlayingControl.Playing; break; case 1: listView = MainWindow.AppWindow.AllMatchesControl.AllMatches; break; case 2: listView = MainWindow.AppWindow.CustomMatchesControl.CustomMatches; break; } }; Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(action)); return listView; } } 返回一个列表,我做错了什么?

2 个答案:

答案 0 :(得分:0)

如您所知,它将通过除UI以外的其他线程完成,只需调用您需要的内容

int currentTab = 0;
MainWindow.AppWindow.TabControl.Dispatcher.Invoke(() => {
  currentTab = MainWindow.AppWindow.TabControl.SelectedIndex;
});

答案 1 :(得分:0)

public ListView CurrentTab
{
    get
    {
         return (ListView)this.Dispatcher.Invoke(
          new Func<ListView>(() => 
          { 
              ListView listView = null;
              int currentTab = tabControl.SelectedIndex;
                switch (currentTab)
                {
                    case 0:
                        listView = new ListView();
                        listView = list_1;
                        break;
                    case 1:
                        listView = list_2;
                        break;
                    case 2:
                        listView = list_3;
                        break;
                }
                return listView;
          }));
    }
}

这可能有用。