【问题标题】:WPF hidding imagesWPF 隐藏图像
【发布时间】:2014-01-08 06:55:45
【问题描述】:

我正在尝试使用以下代码隐藏我目前在 WPF 上的所有图像:

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

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

调用线程无法访问此对象,因为其他线程拥有它

我该如何解决这个错误?

【问题讨论】:

  • 很可能图像是在后台线程上创建的,或者您正试图从后台线程修改它。作为一种解决方案,使用Dispatcher 而不是后台线程在应用程序的主 UI 线程上运行代码。
  • @Rachel 介意展示一个例子吗?
  • 当然,请查看this answer。它用于更新非UI对象,但问题和解决方案仍然相同。
  • @Rachel 我是 WPF 新手,所以该页面上有很多东西我不知道该放在哪里。这些图像已经在 WPF 表单上,所以我不知道为什么它在不同的线程中说它......
  • 此代码是否从新线程或 BackgroundWorker 运行?如果是这样,您需要使用Dispatcher 将更新图像的代码发送到 UI 线程,因为后台线程无法更新不是它创建的对象的属性。如果不是,那么 theImgs 集合是在单独的线程上创建的,代码的逻辑需要更改以从主 UI 线程创建它们。

标签: wpf vb.net image wpf-controls


【解决方案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 
    }
)

【讨论】:

  • 似乎无法将其转换为 VB.net?
  • 我试过 Application.Current.Dispatcher.Invoke(Function(){ theImgs(intX).Visibility = Visibility.Hidden}) 但这似乎不起作用?跨度>
  • 我也试过 Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, New Action(Function() {theImgs(intX).Visibility = Visibility.Hidden})) 这也行不通。
  • 听起来调度员已经对你的第一个异常进行了排序,但肯定还有另一个问题。您可以发布您的 xaml 吗?
【解决方案2】:

试试链接here

下面的代码应该可以正常工作:

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

【讨论】:

  • 我收到错误对象引用未设置为对象的实例。
  • 试试下面的代码: Dispatcher di = Dispatcher.CurrentDispatcher;// InitiliizeComponent(); 旁边在类级别存储 Di 变量 现在尝试使用 di.Invoke(DispatcherPriority.Background, _ New Action(Function() theImgs(intX).Visibility = Visibility.Hidden))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-02
  • 2021-07-30
  • 2013-09-05
  • 2014-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多