开发者

Silverlight HorizontalAlignment not working

开发者 https://www.devze.com 2023-03-13 08:28 出处:网络
I\'m trying to set an Image HorizontalAlignment property in code, not XAML, but it fails to work: Grid grid = new Grid();

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.H开发者_JS百科orizontalAlignment = 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...


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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号