试图从另一个线程访问SelectedIndex
本文关键字:访问 SelectedIndex 线程 另一个 | 更新日期: 2023-09-27 18:08:01
我需要从另一个线程访问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;
}
}
但是我得到
系统。InvalidOperationException
调用线程无法访问对象,因为该对象由另一个线程属性拥有。
我试图通过SelectedIndex
返回一个列表,我做错了什么?
正如你所知道的,它将通过UI以外的另一个线程完成,只需调用你需要的
int currentTab = 0;
MainWindow.AppWindow.TabControl.Dispatcher.Invoke(() => {
currentTab = MainWindow.AppWindow.TabControl.SelectedIndex;
});
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;
}));
}
}