【问题标题】:Why this property isn't visible? Says attachable property can't be found为什么这个属性不可见?说找不到附加属性
【发布时间】:2011-11-14 21:22:54
【问题描述】:

我正在创建带有附加属性的行为。行为应附加到网格:

public class InteractionsBehavior : Behavior<Grid>
{
    public static readonly DependencyProperty ContainerProperty =
        DependencyProperty.RegisterAttached("Container", typeof(Grid), typeof(Grid), new PropertyMetadata(null));

    public static readonly DependencyProperty InteractionsProviderProperty =
        DependencyProperty.RegisterAttached("InteractionsProvider", typeof(IInteractionsProvider), typeof(Grid), new PropertyMetadata(null, OnInteractionsProviderPropertyChanged));

    public Grid Container
    {
        get { return GetValue(ContainerProperty) as Grid; }
        set { this.SetValue(ContainerProperty, value); }
    }

    public IInteractionsProvider InteractionsProvider
    {
        get { return GetValue(InteractionsProviderProperty) as IInteractionsProvider; }
        set { this.SetValue(InteractionsProviderProperty, value); }
    }

现在当我像这样编写 XAML 时出现错误:

<Grid Background="White" x:Name="LayoutRoot" 
          Behaviors:InteractionsBehavior.InteractionsProvider="{Binding InteractionsProvider}">

错误 4 类型上不存在属性“InteractionsProvider” XML 命名空间中的“网格” 'clr-命名空间:Infrastructure.Behaviors;assembly=Infrastructure.SL'。 C:\MainPage.xaml 11 11 Controls.SL.Test

错误 1 ​​未找到可附加属性“InteractionsProvider” 在类型 '交互行为'。 C:\MainPage.xaml 11 11 Controls.SL.Test

【问题讨论】:

    标签: c# silverlight xaml behavior


    【解决方案1】:

    您指定它只能由InteractionsBehavior 附加(“拥有”)。如果您希望能够将其分配给网格,请将 RegisterAttached 行更改为:

    public static readonly DependencyProperty InteractionsProviderProperty =
            DependencyProperty.RegisterAttached("InteractionsProvider", typeof(IInteractionsProvider), typeof(Grid), new PropertyMetadata(null, OnInteractionsProviderPropertyChanged));
    

    (或者在Grid的类层次结构中使用一些基类...)

    【讨论】:

    • 我刚刚编辑了我的帖子 - 这是同一个问题 - 我得到了同样的错误。我想知道班级本身是否有问题? Behavior 是什么意思?
    • @katit 这是一种表达行为——如果你正在使用它,你可能不想要附加属性。您通常会使用 Behavior 或附加属性。如果要使用附加属性,还需要修复 get/set 访问器的规范 - 请参阅:msdn.microsoft.com/en-us/library/ms749011.aspx
    • 我不知道不同的行为类型。现在看来表达行为会更适合我,因为它似乎有“状态”。你回答了我的问题,如果你有关于如何编写表达式行为的好教程,我将不胜感激
    【解决方案2】:

    问题在于您的附加属性的声明。附加属性有 4 个部分:名称、类型、所有者类型和属性元数据。您指定 InteractionsProvider 属性由 Grid 类型拥有(并因此提供)。事实并非如此。将所有者类型(第三个参数)更改为 typeof(InteractionsBehavior)(您在其中声明附加属性的类),切换到静态 get/set 方法而不是属性(因为您使用的是附加属性,而不是依赖项属性),它应该可以按您的预期工作。

    【讨论】:

    • 迈克,我标记了里德的答案。实际上,当我按照命名约定添加 SetInteractionsProvider 和 GetInteractionsProvider 时,它就开始起作用了。但是,这段代码的“静态”性质似乎对我不起作用,我需要探索表达式行为
    猜你喜欢
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    相关资源
    最近更新 更多