rage
rage

Reputation: 1837

Silverlight app freezes when simply adding a textblock to the layoutroot

I cannot understand why in the hell this simple silverlight application freezes up. Here is the code:

namespace test
{
public partial class MainPage : UserControl
{
    TextBlock txtword;
    public MainPage()
    {

        InitializeComponent();

        txtword = new TextBlock();
        txtword.Text = "TEST";

        LayoutRoot.Children.Add(txtword);
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        txtword.Text = "SuperDuper";
    }

}
}

After the textblock is added to the layoutroot if you try to hover or click on the button you can tell that the app has frozen for some reason. Any idea what is going on here??

If i add the text block in the XAML i am able to change its text property in the button click. LayoutRoot.Children.Add() is causing the app to freeze..

Upvotes: 0

Views: 157

Answers (1)

Luke Woodward
Luke Woodward

Reputation: 65024

From reading your comments it seems the XAML in MainPage.xaml is something like the following:

<Grid x:Name="LayoutRoot" Background="White">
    <Button Content="Do stuff" Click="Button_Click" />
</Grid>

After adding the TextBlock, either in code or in XAML, you effectively end up with the following:

<Grid x:Name="LayoutRoot" Background="White">
    <Button Content="Do stuff" Click="Button_Click" />
    <TextBlock Text="TEST" />
</Grid>

Your Grid doesn't specify any ColumnDefinitions or RowDefinitions, so you have a 1 × 1 grid with all child controls of the Grid given the entire width and height of the grid.

As neither your Button nor your TextBlock specify a z-index value (using Canvas.ZIndex), their z-order is defined by their position within the grid's Children. The TextBlock comes after the Button, so it is the one that is 'on top'.

The TextBlock may contain only a tiny amount of text, but the TextBlock itself will still fill the Grid. TextBlocks do not automatically resize to fit the text they contain and nothing else. Your Button appears not to work because the TextBlock is on top of it and receives all of the mouse events. TextBlocks are static controls that do nothing in response to any mouse event, and this should explain why your app is appearing to freeze.

Setting the HorizontalAlignment and/or VerticalAlignment of the TextBlock to a value other than Stretch stops the TextBlock being given the entire width and height of the Grid and allows the Button to receive mouse events.

Upvotes: 1

Related Questions