Resharper Warnings with MVVM

2019-04-03 08:39发布

问题:

As I implement the MVVM pattern with WPF, I'm finding that Resharper is often warning me that certain properties are never used in my ViewModels. The problem is that they are being used, but only by the data binding system. Has anyone else encountered this annoyance and is there a way to help Resharper realize that these properties are, indeed, being used? I am glad, at least, that VS 2010 properly realizes that [Import] tagged members won't "always be null", but hopefully I can fix this issue as well.

回答1:

You can use External Annotations to indicate to Resharper the method is used and thus not to warn you. see the Resharper docs on that here

You need to decorate any such methods with [UsedImplicitlyAttribute]

Before using the attribute you see:

and then after applying the attribute:

[UsedImplicitly(ImplicitUseTargetFlags.WithMembers)]
class NotUsed
{
    public int Field1 { get; set; }
    public int Field2 { get; set; }
}


回答2:

Use

<UserControl
...
xmlns:vm="clr-namespace:YourProject.ViewModels" mc:Ignorable="d"
d:DataContext="{d:DesignInstance vm:SomeClassViewModel}">

It 'stick's View to Model. In View you could see model properties and vice versa - in model properties should be used.



回答3:

You can try two different options. One is to reduce the severity of the Resharper inspection to "Hint". The other option is to use the "Suppress inspection with comment" item Resharper provides for the properties that generate the warning that you know are being used. Personally, I'd go with reducing the severity to "Hint".



回答4:

A crude workaround would be to disable the warning altogether:

Under Resharper > Options > Code Inspection > Inspection Severity, set the warning level for this item to "Do not show".

This is obviously not ideal, but it depends on your level of annoyance with the false positives.



回答5:

This is because of weakly-typed nature of XAML bindings.

To make ReSharper able to resolve what properties of VM you use from XAML view, you need to introduce data context type annotatations for {Binding}s in markup. See the "Binding assistance" section in this blog post for details. You will get correct usage analyse, navigation and refactorings support when ReSharper will known data context type.

ReSharper also knows about OneWay/OneWayToSource/TwoWay bindings modes and marks properties getters/setters/both accessors as used respectively.



回答6:

Are the properties public or internal? In my experience, ReSharper doesn't warn on pubic (since there's no way it could tell that the members aren't being used externally) but it will warn on internal members since they can only be used within that assembly (InternalsVisibleTo notwithstanding)