2011-02-03 23 views
0

當我設置WindowState = Maximized時,得到一個奇怪的錯誤(工作正常如果我將它設置爲Normal,然後全屏!!)。調試給了我一個討厭的異常,並希望在這裏得到一些指針。lineNumbersCanvas.Width WindowState = Maximized時造成異常

例外:

System.NullReferenceException was unhandled 
Message=Object reference not set to an instance of an object. 
Source=SyntaxHighlight 
StackTrace: 
at SyntaxHighlight.SyntaxHighlightBox.<.ctor>b__0(Object s, RoutedEventArgs e) in  
C:\Test\SyntaxHighlight\src\SyntaxHighlightBox.xaml.cs:line 67 

SyntaxHighlighBox.xaml.cs

public SyntaxHighlightBox() { 
    InitializeComponent(); 

    MaxLineCountInBlock = 100; 
    LineHeight = FontSize * 1.3; 
    totalLineCount = 1; 
    blocks = new List<InnerTextBlock>(); 

    Loaded += (s, e) => { 
     renderCanvas = (DrawingControl)Template.FindName("PART_RenderCanvas", this); 
     lineNumbersCanvas = (DrawingControl)Template.FindName("PART_LineNumbersCanvas", this); 
     scrollViewer = (ScrollViewer)Template.FindName("PART_ContentHost", this); 

     lineNumbersCanvas.Width = GetFormattedTextWidth(string.Format("{0:0000}", totalLineCount)) + 5; 

     scrollViewer.ScrollChanged += OnScrollChanged; 

     InvalidateBlocks(0); 
     InvalidateVisual(); 
    }; 

    SizeChanged += (s, e) => { 
     if (e.HeightChanged == false) 
      return; 
     UpdateBlocks(); 
     InvalidateVisual(); 
    }; 
+0

而哪些是第67行? – 2011-02-03 00:55:43

回答

1

這是我遇到的SyntaxHighlightBox以及一個錯誤。 我通過簡單地將Loaded處理程序正在執行的所有操作移至OnApplyTemplate()方法的重寫中來修復它。

public SyntaxHighlightBox() { 
    InitializeComponent(); 

    MaxLineCountInBlock = 100; 
    LineHeight = FontSize * 1.3; 
    totalLineCount = 1; 
    blocks = new List<InnerTextBlock>(); 

    // The Loaded handler is not needed anymore. 

    SizeChanged += (s, e) => { 
     if (e.HeightChanged == false) 
      return; 
     UpdateBlocks(); 
     InvalidateVisual(); 
    }; 

    TextChanged += (s, e) => { 
     UpdateTotalLineCount(); 
     InvalidateBlocks(e.Changes.First().Offset); 
     InvalidateVisual(); 
    }; 
} 

public override void OnApplyTemplate() 
{ 
    base.OnApplyTemplate(); 

    // OnApplyTemplate() is called after Loaded, and this is where templated parts should be retrieved. 

    renderCanvas = (DrawingControl)Template.FindName("PART_RenderCanvas", this); 
    lineNumbersCanvas = (DrawingControl)Template.FindName("PART_LineNumbersCanvas", this); 
    scrollViewer = (ScrollViewer)Template.FindName("PART_ContentHost", this); 

    lineNumbersCanvas.Width = GetFormattedTextWidth(string.Format("{0:0000}", totalLineCount)) + 5; 

    scrollViewer.ScrollChanged += OnScrollChanged; 

    InvalidateBlocks(0); 
    InvalidateVisual(); 
}