[英]How can i get the value of the custom property?
我在尋找一種將自定義屬性添加到xaml控件的方法。 我找到了以下解決方案: 將自定義屬性添加到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)
始終為假...怎么了?
首先,看來您的代碼中充滿了錯誤,所以我不確定,如果沒有正確地復制它,或者是什么原因。
那么您的示例出了什么問題?
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);
}
if ((bool)child.GetValue(Class1.IsTestProperty))
{
// ...
}
foreach (FrameworkElement child in Container.Children)
{
// ...
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.