How to add NotNullAttribulte to elements in XAML

Hi,

How can I add NotNullAttribute to elements in XAML.

Here is a psudo code.

*** XAML ***
<Window x:Class="MyWindow" ...>
....
<Button x:Name="btnOK">OK</Button>
...
</Window>

*** CS ***
public partial MyWindow : Window
{
...
void MyMethod()
{
var w = btnOK.ActualWidth;//ReSharper indicates "Possible Null Reference Exception" in this line.
}
}

I wouldn't like ReSharper to indicate the warnig as to elements in XAML.

The following is a workaround I found.

*** XAML ***
<Window x:Class="MyWindow" ...>
....
<Button x:Name="_btnOK">OK</Button>
...
</Window>

*** CS ***
public partial MyWindow : Window
{
[NotNull]
public Button btnOK;

public MyWindow()
{
InitializeComponent();
if (_btnOK != null)
btnOK = _btnOK;
}

...
void MyMethod()
{
var w = btnOK.ActualWidth;//no warnings
}
}

Are there other good ideas?

Thank you.

 

2 comments

Dear John,

Thank you for your comment.

I wondered whether it worked in this case because MyProject dosen't refer MyProject itself.

However, it works.

It's the very information I'm looking for.

Thank you so much again.

0

Please sign in to leave a comment.