2011-04-18 69 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