【问题标题】:How to set a clr-namespace property programatically in WPF如何在 WPF 中以编程方式设置 clr-namespace 属性
【发布时间】:2012-09-24 07:05:48
【问题描述】:

我是 WPF 的新手,所以我不确定问题的标题是否正确或有意义,如果它可以变得更相关,请进行编辑。我在我的应用程序中使用 Kinect.Toolbox MouseControl。对于使用磁性控件,我遇到了问题。我知道我可以通过添加在 XAML 中定义它们:

<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
    }

但是我无法理解如何以编程方式设置它们。

【问题讨论】:

    标签: c# wpf xaml kinect.toolbox


    【解决方案1】:

    这看起来像attached property

    要设置它,你会做类似的事情

    tb.SetValue(MagneticPropertyHolder.IsMagneticProperty, true);
    

    或者可能

    MagneticPropertyHolder.SetIsMagnetic(tb, true);
    

    快速浏览一下 Kinect Toolbox 源代码表明,两者都可以。第二个是更安全的类型。

    更多信息请参见How to I access an attached property in code behind?

    【讨论】:

      猜你喜欢
      • 2021-06-22
      • 2023-01-03
      • 2020-12-02
      • 2021-05-20
      • 1970-01-01
      相关资源
      最近更新 更多