1

I'm try to do a bit of WPF, only really done windows forms until now and not a lot of that...

All I'm trying to do is to dynamically within code (not xaml) set a button to show an image and set the size of the button to auto size to the image.

The code below loads the image but it goes when the mouse is over the button and the button doesn't auto size to the image.

tbButtonPicture contains a local path on the PC to a bitmap e.g. C:\temp\my Artwork\test1.bmp

This what I have thus far which sits inside a loop:

Console.WriteLine(tbButtonPicture);
System.Windows.Controls.Button newBtn = new Button();
//newBtn.Content = i.ToString();
newBtn.Background = new ImageBrush(new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), tbButtonPicture)));
newBtn.Name = "Button" + i.ToString();
sp.Children.Add(newBtn);

i++;
4
  • sorry Nemesv, I have updated it with a question! Commented Feb 15, 2012 at 12:05
  • 3
    Why just not add some ItemsControl derived class and bind it to container of data? Commented Feb 15, 2012 at 12:05
  • Hi Serge, thank you for your suggestion but I don't have a clue how I would do this! I will google ItemsControl. it was easier when you just set a property in winforms :( I think even this simple task is giving me a lot of new things to lean... Commented Feb 15, 2012 at 12:12
  • 2
    Read the overviews, especially the ones on data binding and data templating. Commented Feb 15, 2012 at 12:37

1 Answer 1

2

Wrap your image in an Image control and set this as the button content and you should have your desired effect.

  System.Windows.Controls.Button newBtn = new Button();
  Image imageControl = new Image();
  imageControl.Source = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), tbButtonPicture));
  newBtn.Content = imageControl;
  newBtn.Name = "Button" + i.ToString();
  sp.Children.Add(newBtn);

  i++;

But I totally agree with above comments: try to solve your issues in xaml its much more easier. Read the suggested resources, they are really helpful.

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

Comments

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.