我正在寻找一种将自定义属性添加到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