2012-10-03 89 views
2

我是WPF新手,所以我不確定問題的標題是否正確或有意義,請編輯它是否可以獲得更多相關性。我在我的應用程序中使用Kinect.Toolbox MouseControl。對於使用磁控制器,我有一個問題。我知道,我可以通過添加在XAML定義它們:如何在WPF中以編程方式設置clr-namespace屬性

<Page ... 
    xmlns:local ="clr-namespace:Kinect.Toolbox;assembly=Kinect.Toolbox"> 
    ... 
<Button local:MagneticPropertyHolder.IsMagnetic="True" ... /> 
.... 

但我需要做的是在代碼中。無論如何要在代碼中設置磁控制器嗎?我可以像這樣在頁面中獲取所有控件:

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject 
    { 
     if (depObj != null) 
     { 
      for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) 
      { 
       DependencyObject child = VisualTreeHelper.GetChild(depObj, i); 
       if (child != null && child is T) 
       { 
        yield return (T)child; 
       } 

       foreach (T childOfChild in FindVisualChildren<T>(child)) 
       { 
        yield return childOfChild; 
       } 
      } 
     } 
    } 

    foreach (Button tb in FindVisualChildren<Button>(this)) 
    { 
      //Set the buttons to be magnetic 
    } 

但是我不明白如何設置它們。

回答

1

這看起來像一個attached property

要設置它,你會做這樣的事情

tb.SetValue(MagneticPropertyHolder.IsMagneticProperty, true); 

或可能

MagneticPropertyHolder.SetIsMagnetic(tb, true); 

在Kinect的工具箱源代碼快速瀏覽表明,無論是可行的。第二種更安全。

請參閱How to I access an attached property in code behind?瞭解更多信息。

相關問題