Search code examples
c#wpfstaticdependency-propertiesnon-static

An alternative way around 'Cannot access non-static property in static context' using dependency property


I have a string source that I am attempting to read in from my xaml to my view and assign to a DependencyProperty. I am getting an error Cannot access non-static property 'Source' in static context, I understand this error but I cannot work out how to get around it. If someone could suggest how I can update the Source to the value of source please

public string Source
{
    get { return (string)GetValue(SourceProperty); }
    set { SetValue(SourceProperty, value); }
}

public static readonly DependencyProperty SourceProperty = 
    DependencyProperty.Register(
            nameof(Source),
            typeof(string),
            typeof(TagsIndicator),
            new PropertyMetadata(null, ReadInSource));            

private static void ReadInSource(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
     string source = e.NewValue.ToString();

     Source = source; // Error here: Cannot access non-static property 'Source' in static context
}

Solution

  • Taking your question literally, you simply need to cast the d parameter for the method:

    private static void ReadInSource(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        TagsIndicator tagsIndicator = (TagsIndicator)d;
        string source = e.NewValue.ToString();
    
        tagsIndicator.Source = source; // Error here: Cannot access non-static property 'Source' in static context
    }
    

    That would make the error go away.

    BUT!

    If that's all your callback is going to do, it seems like the real solution is to just delete the callback method (and of course, don't register it with the DependencyProperty).

    The whole point of the dependency property system is that WPF is managing the property values on your behalf. That callback is only called when the property has already been changed by the dependency property system, e.g. via a binding or setting the property directly itself (which, in the property setter, calls DependencyObject.SetValue()).

    Setting the property again, to the same value that it's just been set to, in response to the property having been set, does not seem to make sense to me.

    Barring some specific need you haven't described in your question, you can just delete that method altogether. (And even if you do have such a need, you should ask a different question about that, because it seems likely you're going about serving that need incorrectly, given the code it led you to.)