我正在尋找一種將自定義屬性添加到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)
總是錯誤的......怎麼了?
Class1.GetIsTestProperty(child) – dnr3 2013-04-23 07:46:37
@ dnr3感謝回覆......但它總是返回false – David 2013-04-23 07:49:38
你檢查了孩子本身嗎?我的意思是它確實指向堆棧面板內的組合框?我試過你的代碼,雖然我在Container.Children上使用了foreach而不是你的Helpers類,並且它返回true,因爲第一個組合框 – dnr3 2013-04-23 08:09:13