1
votes

I'm trying to set an Image HorizontalAlignment property in code, not XAML, but it fails to work:

Grid grid = new Grid();
grid.ColumnDefinitions.Add(new ColumnDefinition());
grid.ColumnDefinitions.Add(new ColumnDefinition());

Image img = new Image() { Source = new Uri("myImage.png") };
Grid.SetColumn(img, 1);
img.HorizontalAlignment = HorizontalAlignment.Right;

grid.Children.Add(img);

This code should create a grid with a single row and two columns, then the image should be added to the second column and be anchored all the way to the right, but the image stays anchored on the left side of the second column.

How can this be? VerticalAlignment works correctly on the image...

2

2 Answers

1
votes

The default value of an Image.Stretch property is Stretch.Uniform. It sounds to me that you want it set to Stretch.None.

 img.Stretch = Stretch.None

Things will then behave as you expect.

1
votes

Well your "Image" line seems to miss something, however that doesn't seem the problem. I think the problem is that the grid changes the size of its elements, because of this the image seems to keep the whole "cell" size. Give your image some small width and height and see what happens.

or check this:

Grid grid = new Grid();
grid.ColumnDefinitions.Add(new ColumnDefinition());
grid.ColumnDefinitions.Add(new ColumnDefinition());

Image img = new Image() 
    { Source = new BitmapImage(new Uri("SaveIcon.PNG", UriKind.Relative)) };
img.Width = 32D;
img.Height = 32D;

Grid.SetColumn(img, 1);
img.HorizontalAlignment = HorizontalAlignment.Right;

grid.Children.Add(img);

LayoutRoot.Children.Add(grid);