0

当我设置我的 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

语法HighlighBox.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();
    };
4

1 回答 1

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();
}
于 2015-02-16T10:45:23.790 回答