Search code examples
c#wpfnullreferenceexceptioninkcanvasxceed

When inkcanvas color change, I got Null exception error Only in event colorpicker_SelectedColorChanged()


I'm making simple paint programm using inkcanvas with c# WPF. I'm using XceedWpfToolkit. It works well.

When I change my inkcanvas pen stroke color with colorpicker, I got some problem.

Null exception error occur only in event colorpicker_SelectedColorChanged(). In other event below code works fine.

        inkcanvas1.DefaultDrawingAttributes.Color = mypenbrush.Color;

I checked mypenbrush.Color is not Null. It has vaule. But below code makes error( "ONLY IN EVENT colorpicker_SelectedColorChanged()" ). For three hours I try to see why. But I never know till now.

private void colorpicker1_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color?> e)
    {
        mypenbrush = new SolidColorBrush();
        mypenbrush.Color = (Color)colorpicker1.SelectedColor;
        inkcanvas1.DefaultDrawingAttributes.Color = mypenbrush.Color;
    }

Here is color picker setting in XAML

<xctk:ColorPicker x:Name="colorpicker1" Width="60" ShowRecentColors="True" SelectedColor="Black" SelectedColorChanged="colorpicker1_SelectedColorChanged" ShowAvailableColors="False"/>

Solution

  • I did a quick test, and what I noticed is that when I initially launch the project, the ColorPicker_SelectedColorChanged event is called while the InkCanvas hasn't loaded yet and is therefore still null. This is what caused the error.

    If I check if InkCanvas is not null prior to assigning it the PenBrush, it works fine.

    private void ColorPicker_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color?> e)
    {
        myPenBrush = new SolidColorBrush();
        myPenBrush.Color = (Color)colorpicker1.SelectedColor;
    
        if (myInkCanvas != null)
            myInkCanvas.DefaultDrawingAttributes.Color = myPenBrush.Color;
    }