2013-04-23 71 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