Minh-Thanh Hoang
Minh-Thanh Hoang

Reputation: 556

Image displays differently in XAML vs. C#

I want to show an image in a Grid

Only the image shows when I use this XAML:

<Image Source="/Assets/O.png"
       Grid.Column="6"
       Grid.Row="5"/>

In C# it shows the picture with a border outside:

Image img = new Image();
BitmapImage bi = new BitmapImage();
bi.UriSource = new Uri("/Assets/O.png", UriKind.Relative);
img.Stretch = Stretch.Fill;
img.Source = bi;
Grid.SetColumn(img, 6);
Grid.SetRow(img, 7);
gridGameBoard.Children.Add(img);

Image img1 = new Image();
img1.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/Assets/X.png", UriKind.Relative));
Grid.SetColumn(img1, 4);
Grid.SetRow(img1, 4);
gridGameBoard.Children.Add(img1);

I tried googling to find any differences between BitmapImage and other Image types but was unsuccessful.

Upvotes: 0

Views: 94

Answers (1)

Igor Kulman
Igor Kulman

Reputation: 16361

The problem is the Stretch property of your Image. In XAML, you do not define it, so a default value of Uniform is used. In C# code you have img.Stretch = Stretch.Fill;

My guess is that the border is in the image, but in the C# code with Fill the image is scaled down, the XAML variant with Uniform scales up the image and centers it so the border is not visible.

Upvotes: 1

Related Questions