【问题标题】:How can i get the value of the custom property?如何获取自定义属性的值?
【发布时间】: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


【解决方案1】:

首先,您的代码似乎充满了错误,所以我不确定您是否没有正确复制它,或者是什么原因。

那么你的例子有什么问题?

  • 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)
{
   // ...
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 2011-07-03
    • 1970-01-01
    • 2010-10-29
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    相关资源
    最近更新 更多