-4

When I'm writing my Button, which is inherited from the button, I set the ControlTemplate using an image, the source is x:bind to a string property in code-behind, like the screenshot below:

<Grid x:Name="rectangle1">
    <Image Source="{x:Bind aCheckImage}" //Error Here
            Stretch="UniformToFill"
            HorizontalAlignment="Center"
            VerticalAlignment="Center">
    </Image>
</Grid>

Why it throws an error that is "Object reference not set to an instance of an object" in compile. How to fix it?

lindexi
  • 4,182
  • 3
  • 19
  • 65
linxiao
  • 11
  • 5

1 Answers1

-2

@Vijay Nirmal gives me a way to solve it.

If you want to bind the image source to other value that you should sure your value in the code. I will write it below.

    public static readonly DependencyProperty aCheckImageProperty = DependencyProperty.Register(
        "aCheckImage", typeof(BitmapSource), typeof(MainPage), new PropertyMetadata(default(BitmapSource)));

    public BitmapSource aCheckImage
    {
        get { return (BitmapSource) GetValue(aCheckImageProperty); }
        set { SetValue(aCheckImageProperty, value); }
    }

I should set it in constructor.

    public MainPage()
    {
        InitializeComponent();

        aCheckImage = new BitmapImage(new Uri("ms-appx:///Assets/LockScreenLogo.scale-200.png"));
    }

If you want to know how to write uri, please see https://msdn.microsoft.com/zh-cn/library/windows/apps/xaml/hh965322(v=win.10).aspx And then I can bind it in XAML.

    <Grid x:Name="rectangle1">
        <Image Source="{x:Bind aCheckImage}" 
               Stretch="UniformToFill"
               HorizontalAlignment="Center"
               VerticalAlignment="Center">
        </Image>
    </Grid>
lindexi
  • 4,182
  • 3
  • 19
  • 65