Search code examples
c#wpfxamldatacontext

WPF :: DataContext Is throwing "Not Set To An Instance" When Pointing to a STATIC class


I am following the guidance in this Microsoft post for setting up Ribbon controls with static properties as their DataContext to bind the UI to a datamodel.

The relevant XAML looks like so:

<Ribbon>
  <RibbonGroup Header="Group1">
    <RibbonToggleButton DataContext="{x:Static vm:WordModel.Bold}"/>
  </RibbonGroup>
</Ribbon>

... and the class for the DataContext:

public static class WordModel
{
  private static readonly object LockObject = new object();
  private static readonly Dictionary<string, ControlData> _dataCollection = 
     new Dictionary<string, ControlData>();

  public static ControlData Bold
  {
     get
     {
        lock (LockObject)
        {
           const string key = "Bold";
           if (!_dataCollection.ContainsKey(key))
           {
              var data = new ToggleButtonData()
              {
                 Command = EditingCommands.ToggleBold,
                 IsChecked = false,
                 KeyTip = "B",
                 SmallImage = Application.Current.Resources["BoldIcon"] as DrawingImage,
                 ToolTipDescription = "Toggles the Bold font weight on the current selection.",
                 ToolTipTitle = "Bold (Ctrl + B)",
              };
              _dataCollection[key] = data;
           }
           return _dataCollection[key];
        }
     }
  }
}

... which is a static class and property. Why would the compiler be giving me the blue squiggly and grousing about "Object reference not set to an instance of an object"? I am setting the DataContext to point to a static reference with the {x:Static ...} bit, am I not?

I'm sure I'm missing something simple here, but darned if I know what it is.


Solution

  • Because of the "thou shouldst reconsider deleting answered questions" recommendation, I'm posting the answer here and accepting my shame publicly. :-)

    The problem was in the setter of SmallImage:

      private ImageSource _smallImage ;
      public ImageSource SmallImage
      {
         get
         {
            return _smallImage;
         }
    
         set
         {
            if (_smallImage.Equals(value)) return;
            _smallImage = value;
            NotifyPropertyChanged(() => SmallImage);
         }
      }
    

    _smallImage was initially null, just as you'd expect, and null.Equals(value) doesn't work well, obviously. I changed that line to

    if (_smallImage == value) return;
    

    and all is well with the world.