2011-04-18 115 views
2

查找器名称,我发现我使用的WPF解决方案 - 尼斯找到名称代码片段:从非UI线程

public static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject 
    { 
     for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) 
     { 
      var child = VisualTreeHelper.GetChild(parent, i); 
      string controlName = child.GetValue(Control.NameProperty) as string; 
      if (controlName == name) 
      { 
       return child as T; 
      } 
      else 
      { 
       T result = FindVisualChildByName<T>(child, name); 
       if (result != null) 
        return result; 
      } 
     } 
     return null; 
    } 

但这仅适用于如果我是在UI线程上。

我有另一个线程播放结束同步的音频文件。我想使用上面的代码在ui线程上设置dep属性,但是我不断收到一个跨线程错误。

即使试图简单:

SoundFXPad selectedSoundFXPad = (SoundFXPad)m_parent.FindName("panelC" + numbervar); 

给了我同样的错误

我见过的所有其他线程安全的WPF调度,调用代码假设你已经知道该控件的名称。有没有一种方法可以用线程安全的方式使用上面的代码来影响另一个需要“找到”名称的线程的UI控件?

谢谢!

回答

1

每个应用程序通常有一个UI线程(通常;您可以创建多个,但不常见)。所以你不需要控制名称来找到调度员 - 试试这个:

Application.Current.Dispatcher.Invoke(new Action(
    delegate { 
     // Put code that needs to run on the UI thread here 
    })); 
+0

非常好!这就是诀窍!只需要在最后添加一个额外的右括号,我现在有喜悦!感谢您及时的回复! – sunriser 2011-04-18 03:09:02