2013-12-19 40 views
0

我想用下面这段代码隐藏我在我的WPF所有图片我目前有:WPF hidding图像

Dim theImgs() As Controls.Image = {picNextTopic1, picNextTopic2, picNextTopic3, picNextTopic4, picNextTopic5, picNextTopic6, picNextTopic7, picNextTopic8, picNextTopic9, picNextTopic10, picNextTopic11, picNextTopic12, picNextTopic13, picNextTopic14, picNextTopic15, picNextTopic16} 

Dim intX As Integer = 0 

Do Until intX = theImgs.Length 
    Try 
     theImgs(intX).Visibility = Visibility.Hidden 
     intX += 1 
    Catch ex As Exception 
     MsgBox(ex.Message) 
    End Try 
Loop 

但是,当运行代码时上面我得到这个错误:

的调用线程无法访问此对象,因为不同的线程拥有它

我该如何解决这个错误?

+1

最有可能无论是图像在后台线程创建,或者你想从后台线程修改。作为解决方案,使用'Dispatcher'而不是后台线程来运行应用程序的主UI线程上的代码。 – Rachel

+0

@Rachel介意示例? – StealthRT

+0

当然,看看[这个答案](http://stackoverflow.com/a/8759160/302677)。它用于更新非UI对象,但问题和解决方案仍然相同。 – Rachel

回答

1

变化:

theImgs(intX).Visibility = Visibility.Hidden; 

要:

C#

Application.Current.Dispatcher.Invoke(new Action(() => 
    { 
     theImgs[intX].Visibility = Visibility.Hidden; 
    }); 

VB

Application.Current.Dispatcher.Invoke(
    Function(){ 
     theImgs(intX).Visibility = Visibility.Hidden 
    } 
) 
+0

不能将其转换成VB.net? – StealthRT

+0

我试过** Application.Current.Dispatcher.Invoke(函数(){theImgs(intX).Visibility = Visibility.Hidden})**但似乎没有工作? – StealthRT

+0

而且我也试过** Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,New Action(Function(){theImgs(intX).Visibility = Visibility.Hidden}))**,那也不起作用。 – StealthRT

0

尝试链接here

下面的代码应该很好地工作:

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, _ 
New Action(Function() theImgs(intX).Visibility = Visibility.Hidden)) 
+0

我得到错误**对象引用未设置为对象的实例** – StealthRT

+0

请尝试以下代码: Dispatcher di = Dispatcher。CurrentDispatcher; // InitlizeComponent();旁边; 商店在类级别的变量迪 现在试着用 di.Invoke(DispatcherPriority.Background,_ 新动作(功能()theImgs(INTX).Visibility = Visibility.Hidden)) –