2013-04-23 67 views
0

我正在寻找一种将自定义属性添加到xaml控件的方法。我发现这个解决方案:Adding custom attributes to an element in XAML?我如何获得自定义属性的值?

的Class1.cs:

public static Class1 
{ 
    public static readonly DependencyProperty IsTestProperty = 
     DependencyProperty.RegisterAttached("IsTest", 
              typeof(bool), 
              typeof(Class1), 
              new FrameworkPropertyMetadata(false)); 

    public static bool GetIsTestProperty(UIElement element) 
    { 
     if (element == null) 
     { 
      throw new ArgumentNullException("element"); 
     } 

     return (bool)element.GetValue(IsTestProperty); 
    } 

    public static void SetIsTestProperty(UIElement element, bool value) 
    { 
     if (element == null) 
     { 
      throw new ArgumentNullException("element"); 
     } 

     element.SetValue(IsTestProperty, value); 
    } 
} 

UserControl.xaml

<StackPanel x:Name="Container"> 
    <ComboBox x:Name="cfg_Test" local:Class1.IsTest="True" /> 
    <ComboBox x:Name="cfg_Test" local:Class1.IsTest="False" /> 
    ... 
... 

现在是我的问题,我怎样才能得到属性的值?

现在我想读取StackPanel中所有元素的值。

// get all elementes in the stackpanel 
foreach (FrameworkElement child in 
      Helpers.FindVisualChildren<FrameworkElement>(control, true)) 
{ 
    if(child.GetValue(Class1.IsTest)) 
    { 
     // 
    } 
} 

child.GetValue(Class1.IsTest)总是错误的......怎么了?

+0

Class1.GetIsTestProperty(child) – dnr3 2013-04-23 07:46:37

+0

@ dnr3感谢回复......但它总是返回false – David 2013-04-23 07:49:38

+0

你检查了孩子本身吗?我的意思是它确实指向堆栈面板内的组合框?我试过你的代码,虽然我在Container.Children上使用了foreach而不是你的Helpers类,并且它返回true,因为第一个组合框 – dnr3 2013-04-23 08:09:13

回答

0

首先,看起来,你的代码充满了错误,所以我不确定,如果你没有正确地复制它,或者是什么原因。

那么你的例子中有什么错?

  • DependencyProperty的getter和setter被错误地创建。 (不应该有“财产”附加到名称。)它chould是:
public static bool GetIsTest(UIElement element) 
{ 
    if (element == null) 
    { 
     throw new ArgumentNullException("element"); 
    } 

    return (bool)element.GetValue(IsTestProperty); 
} 

public static void SetIsTest(UIElement element, bool value) 
{ 
    if (element == null) 
    { 
     throw new ArgumentNullException("element"); 
    } 

    element.SetValue(IsTestProperty, value); 
} 
  • 其次,无论是StackPanel中的孩子控件的名称相同,那不是可能的。
  • 第三,你错误地在你的foreach语句中获得了财产。这应该是:
if ((bool)child.GetValue(Class1.IsTestProperty)) 
{ 
    // ... 
} 
  • 可以肯定,你的Helpers.FindVisualChildren工作正常。你可以改用以下:
foreach (FrameworkElement child in Container.Children) 
{ 
    // ... 
} 

希望这有助于。

+0

好的谢谢,DependencyProperty错了...... – David 2013-04-23 08:35:54