1
votes

I really need help. I am dynamically creating a grid control in my code behind, then adding it to the children of the containing control that was defined in the xaml. Now, everything is dynamically being created as expected, but unfortunately when I set the style in the same way I set the text of the textboxes which I add to the grid and position in row/columns accordingly it doens't work. Notice the following code:

        AddTextBlock(7, col, String.Format("{0:0}%", finances.PrivateDaysPercent), "GridValueStyle");


    TextBlock AddTextBlock( int row, int column, string text, string style)
    {
        Style s = Resources[style] as Style;
        TextBlock tb = new TextBlock() { Text = text};
        tb.Style = s;
        Grid.SetColumn(tb, column);
        Grid.SetRow(tb, row);
        grid.Children.Add(tb);
        return tb;
    }

    <Style x:Key="GridValueStyle" TargetType="TextBlock" BasedOn="{StaticResource ContentTextStyle}" >
        <Setter Property="Margin" Value="2,1" />
        <Setter Property="HorizontalAlignment" Value="Right"/>
        <Setter Property="VerticalAlignment" Value="Center" />
    </Style>

The style should clearly be setting, but it isn't. The style is defined correctly in the resource dictionary and added to app.xaml. I know it works becuase I use this style in another navigation page and it applies perfectly to a statically created grid in xaml.

1
I forgot to mention... the textblock should also automatically be inheriting the white foreground text style's being propogated from somewhere as other text on the page does, but it doesn't... any ideas?allen brubaker

1 Answers

2
votes

You should note that using Resources[style] only attempts to retrieve the key from that specific ResourceDictionary. It does not hunt up the tree of elements looking for the value of style in other ResourceDictionary objects. This often takes devs by surprise since that is what happens when {StaticResource ....} is used in xaml.

I would guess the code you have included is in a UserControl hence for "GridValueStyle" to be found it must be specifically in the UserControl's Resources. If it's in the resources of a child (such as the <Grid.Resources> of the "LayoutRoot" which is common) then it won't be found, nor will it be found if it is in the App.Xaml.