【问题标题】:Trying to access to SelectedIndex from another thread [duplicate]试图从另一个线程访问 SelectedIndex [重复]
【发布时间】:2016-09-21 13:45:30
【问题描述】:

我需要从另一个线程访问TabControlSelectedIndex 属性,我尝试使用这样的Dispatcher

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

但我明白了

System.InvalidOperationException

调用线程无法访问该对象,因为该对象由另一个线程属性拥有。

我试图通过SelectedIndex返回一个列表,我做错了什么?

【问题讨论】:

  • 你能告诉你为什么需要通过不同的线程访问 selectedindex 吗?如果你访问如何同步它们?换句话说,如果你在值更改之前从另一个线程返回 selectedindex,如何你能抓住价值吗?
  • @FreeMan '因为我需要返回一个特定的列表,每个选项卡都包含一个列表,所以如果选择选项卡 2,我需要返回列表 CustomMatches。并且应用程序有不同的线程调用CurrentTab
  • 你必须使用 TabControl 所属的 Dispatcher。因此,如果您在不同的线程上,并且您写Application.Current.Dispatcher,它不一定会为您提供您正在寻找的调度程序。每个 FrameworkElement 都有一个包含其调度线程的属性。

标签: c# .net wpf


【解决方案1】:

如您所知,它将通过 UI 之外的另一个线程完成,只需调用您需要的内容

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

【讨论】:

  • 我没有任何 InvokeRequired
  • 对不起,我错过了它是 WPF。原始答案已更新。
【解决方案2】:
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;
          }));
    }
}

这可能有效。

【讨论】:

  • 谢谢,但这将返回一个列表,其中属性内有异常:imgur.com/a/DPirO
  • 有趣的是它对我有用。
  • 有什么建议可以解决这个问题吗?
猜你喜欢
  • 1970-01-01
  • 2021-07-30
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
相关资源
最近更新 更多