在XAML中无法识别AttachedProperty(编译错误)

时间:2014-08-21 13:01:44

标签: wpf xaml winrt-xaml windows-phone-8.1

当我尝试将附加属性添加到listview控件时,我遇到了构建错误。

我的代码有什么问题导致它无法构建?

我的代码如下:

XAML:

xmlns:attachedProperties="using:MyNamespace.AttachedProperties"

<ListView x:Name="ContactList" 
          attachedProperties:CategoryHelper.Category="{Binding SelectedCategory, Mode=TwoWay}" />

代码:

namespace MyNamespace.AttachedProperties
{
    public class CategoryHelper : DependencyObject
    {
        public static readonly DependencyProperty CategoryProperty = DependencyProperty.RegisterAttached(
            "Category", typeof(Category), typeof(CategoryHelper), new PropertyMetadata(null, OnPropertyChangedCallBack));

        private static void OnPropertyChangedCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            throw new System.NotImplementedException();
        }

        public static void SetCategory(ListView listview, Category category)
        {
            listview.SetValue(CategoryProperty, category);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

你错过了吸气剂。它应该是这样的:

        public static Category GetCategory(DependencyObject obj)
        {
            return (Category)obj.GetValue(CategoryProperty);
        }

        public static void SetCategory(DependencyObject obj, Category value)
        {
            obj.SetValue(CategoryProperty, value);
        }

        // Using a DependencyProperty as the backing store for Category.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CategoryProperty =
            DependencyProperty.RegisterAttached("Category", typeof(Category), typeof(CategoryHelper), new PropertyMetadata(0));

您可以使用内置代码段propa来生成属性。

答案 1 :(得分:0)

我看不到DependencyProperty的getter和setter,如

public static void SetMyContent(DependencyObject obj, string val)
    {
        obj.SetValue(MyContentProperty, val);
    }

    public static string GetMyContent(DependencyObject obj)
    {
        return (string)obj.GetValue(MyContentProperty);
    }