简体   繁体   中英

“Attribute 'Dependency' is not valid on this declaration type.” error

Why I receive such message?

Attribute 'Dependency' is not valid on this declaration type. It is only valid on 'assembly' declarations.

public partial class MainWindow : Window
{
    private OverviewViewModel _vm;

    [Dependency]
    public OverviewViewModel VM
    {
        set
        {
            _vm = value;
            this.DataContext = _vm;
        }
    }

You are probably using the wrong attribute: DependencyAttribute

Indicates when a dependency is to be loaded by the referring assembly [...]

and can only be applied to assemblies (and not to properties like you are trying), eg:

[assembly: Dependency(/*...*/)]

Attributes are allowed to declare what they can apply to (via AttributeUsageAttribute). The default is anything , but in this case it is "assembly", meaning: you can only apply this at the assembly level, which you do via:

[assembly:Dependency(...)]

If this is your own attribute, check the AttributeUsageAttribute associated with it, and ensure it includes properties (using the pipe | to apply "or").

If it is not your attribute, double-check the intended usage - you might be using it wrong.

Try including the getter:

 private OverviewViewModel _vm; [Dependency] public OverviewViewModel VM { set { _vm = value; this.DataContext = _vm; } get { return _vm; } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM