当指向STATIC类时,WPF :: DataContext正在抛出“未设置为实例”

时间:2015-04-08 18:31:22

标签: c# wpf xaml datacontext

我遵循this Microsoft post中的指导,将Ribbon控件设置为静态属性作为DataContext将UI绑定到数据模型。

相关的XAML如下所示:

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

...以及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];
        }
     }
  }
}

...这是 静态 类和属性。为什么编译器会给我一个关于“Object reference not set to an instance of an object”的蓝色波浪形和咕噜声?我将DataContext设置为指向带有{x:Static ...}位的静态引用,不是吗?

我确信我在这里遗漏了一些简单的东西,但如果我知道它是什么就会变得很难。

2 个答案:

答案 0 :(得分:1)

由于“你应该重新考虑删除已回答的问题”推荐,我在这里发布答案并公开接受我的耻辱。 : - )

问题在于SmallImage的设置者:

  private ImageSource _smallImage ;
  public ImageSource SmallImage
  {
     get
     {
        return _smallImage;
     }

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

_smallImage最初是null,正如您所期望的那样,null.Equals(value)显然效果不佳。我将该行更改为

if (_smallImage == value) return;

并且全世界都很好。

答案 1 :(得分:0)

这似乎是设计时错误。

每当设计者在设计时访问事物时,可能会触及过程流中对象的构造函数和属性。如果您在此期间无需为其解决问题,请在设计时间内检查以解决问题。

WPF

if (!DesignerProperties.IsInDesignModeProperty)

Silverlight的

if (!DesignerProperties.IsInDesignTool)