Reputation: 3418
I am relatively new to WPF and trying to insert a label computed by an algorithm inside a panel. I create the label in my code. I do not use the designer for the label.
The problem is that when I add the label to the panel, it gets resized when I resize the Window. I want the label to be a fixed height and width. Apparently it is anchored to the bottom of the window (I know that from the usual Winforms behavior).
How can I unanchor it, or give it a fixed size?
EDIT
XAML:
<Window x:Class="TestWrapper.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MyTest" Height="483.833" Width="525" Loaded="Window_Loaded">
<Grid x:Name="MyGrid" Margin="0">
<Grid.Background>
<ImageBrush ImageSource="Resources/Background.jpg" Stretch="Uniform"/>
</Grid.Background>
</Grid>
</Window>
Code:
if (!_initialized)
{
Label lbl = new Label()
{
Content = "Test",
FontSize = 36,
Foreground = new SolidColorBrush(Colors.Red),
Background = new SolidColorBrush(Colors.Black),
HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center,
VerticalAlignment = System.Windows.VerticalAlignment.Top
};
this.MyGrid.Children.Add(lbl);
lbl.Margin = new Thickness(0, this.MyGrid.ActualHeight + lbl.ActualHeight, 0, 0);
this._initialized = true;
}
Upvotes: 0
Views: 369
Reputation: 622
I suggest to use instead the HorizontalAlignment
and VerticalAlignment
.
<Label HorizontalAlignment="Center" VerticalAlignment="Center" Content="Hello World" />
In this way, the label is automatically centered and the size is dynamically adapted by the WPF Engine.
Remember also that a WPF interface should not be developed by code behind, in most of cases, if not always. You can easily use the Xaml to resolve your problem.
Upvotes: 0
Reputation: 34218
If you simply want to hardcode a width and height, explicitly set the Width
and Height
attributes of your label:
<Label Width="100" Height="20">Hello World</Label>
A Grid
will automatically centre and stretch its children, given no other information, and this is the default behaviour you're likely seeing.
(If you provide more code/markup, I can give a more detailed explanation.)
Upvotes: 2