0

I am new to WPF, here I am making a jigsaw game but encountering a problem: I just don't know how to let a image show in a Label in pure code (in XAML, I can do it.), I have searched google a lot but seems that no releated articles regarding this topic. Anyone can help me on this? thx.

My Code Sample:

        Label lbl = new Label();
        lbl.Width = 120;
        lbl.Height = 120;
        lbl.Background = new SolidColorBrush(Colors.YellowGreen);

        BitmapImage myImageSource = new BitmapImage();
        myImageSource.BeginInit(); 
        myImageSource.UriSource = new Uri("Images/test.png",UriKind.Relative); 
        myImageSource.EndInit();

        lbl.Background.SetValue(ImageBrush.ImageSourceProperty, myImageSource);

        myGridContainer.Children.Add(lbl);

well, this code sample can't work. why ? any comment or answer from you will be appreciated , thx.

3
  • I think it's because you've used a SolidColorBrush instead of an ImageBrush. See msdn.microsoft.com/en-us/library/… Commented Sep 4, 2012 at 4:24
  • @Gishu well, when I comment out the code : lbl.Background = new SolidColorBrush(Colors.YellowGreen); , it throws me the exception at lbl.Background.SetValue(ImageBrush.ImageSourceProperty, myImageSource); as "Object reference not set to an instance of an object." Commented Sep 4, 2012 at 4:53
  • use lbl.Background = new ImageBrush() instead. Getting a good WPF book like 'Programming WPF' by IanGriffith, Chris Sells.. will help you code faster. Commented Sep 4, 2012 at 4:58

1 Answer 1

1

You can use BindingOperations.SetBinding to data-bind a DependencyProperty to its source.

See also: How can I create a tiled image in code that is also data-bound?

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, I am a newer, just can't get any options from the article you recommand. I just don't know how to use the BindingOperations.
I have changed some of the cotent, Would you pls have a look? thx.
stackoverflow.com/questions/4586028 I thing you would need to bind the Source property of a Image (which can be the content of the label). To set data bindings in code, refer to this MSDN How to msdn.microsoft.com/en-us/library/ms742863.aspx. Now you just need to use the knowledge to bind Image.Source instead of TextBlock.TextProperty as in the article.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.