Search code examples
c#wpfxamlkinect.toolbox

How to set a clr-namespace property programatically in WPF


I am new with WPF, so I'm not sure if the title of the question is correct or makes any sense, please edit if it can get more relevant. I am using Kinect.Toolbox MouseControl in my application. For using the magnetic controls I have a problem. I know that I can define them in XAML by adding:

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

But I need to do it in the code. Is there anyway to set the magnetic controls in the code? I can get all the controlls in the page like this:

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
    }

However I cannot understand how to set them progmatically.


Solution

  • This looks like an attached property.

    To set it, you'd do something like

    tb.SetValue(MagneticPropertyHolder.IsMagneticProperty, true);
    

    or possibly

    MagneticPropertyHolder.SetIsMagnetic(tb, true);
    

    A quick glance at the Kinect Toolbox source code suggests that either would work. The second is more type safe.

    See How to I access an attached property in code behind? for more information.