【发布时间】:2013-04-16 07:51:11
【问题描述】:
我正在寻找一种将自定义属性添加到 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 感谢您的回复...但它总是返回错误
-
您检查过孩子本身吗?我的意思是它真的指的是堆栈面板内的组合框吗?我尝试了您的代码,尽管我在 Container.Children 上使用了 foreach 而不是您的 Helpers 类,并且它为第一个组合框返回 true
标签: c# wpf attributes dependency-properties custom-attributes