简体   繁体   中英

WPF - How to Center a label's Content inside the label

I created some labels in a for loop on the behind code.
At the beginning it looks like that:

private void SlotLabelCreation(string name)
{
    Label label = new Label();
    label.Name = name;
    label.HorizontalAlignment = HorizontalAlignment.Left;
    label.VerticalAlignment = VerticalAlignment.Top;
    label.Content = "[Free Slot]";
    label.Foreground = Brushes.Gray;
    label.BorderBrush = Brushes.Black;
    label.BorderThickness = new Thickness(1);
    label.Visibility = Visibility.Hidden;
    MainGrid.Children.Add(label);

    //the margin has been inserted later in other code.
}

everything was fine but when I inserted to the label other content which not contains the same amount of letters it looks like that:

sorry about the links.. it's because I can't upload images

http://s27.postimg.org/6halp6p37/pic2.png

I wanted to make all slots the same size so I added a MinWidth property to the labels.
The new result was:

http://s27.postimg.org/6z5r51eo3/pic3.png

now it looks better but I am wondering how could I center the content which inside the label.
Unfortunately I didn't find any solution to solve this problem.

ps, HorizontalAlignment and VerticalAlignment don't solve the problem.

Thanks a lot, Alon P.

您应该使用Horizo​​ntalContentAlignment和VerticalContentAlignment属性

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM