【发布时间】:2016-09-21 13:45:30
【问题描述】:
我需要从另一个线程访问TabControl 的SelectedIndex 属性,我尝试使用这样的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 都有一个包含其调度线程的属性。