簡體   English   中英

如何獲得自定義屬性的值?

[英]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)始終為假...怎么了?

首先,看來您的代碼中充滿了錯誤,所以我不確定,如果沒有正確地復制它,或者是什么原因。

那么您的示例出了什么問題?

  • 您的DependencyProperty的getter和setter被錯誤地創建。 (名稱中不應包含“屬性”。)應為:
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)
{
   // ...
}

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM