Home > Back-end >  Set children of UIelement in C#
Set children of UIelement in C#

Time:03-08

I want to code a button with two texblocks directly on the button in WPF. I would do that in xaml, the code would look something like this:

<Button Grid.Row="0" HorizontalAlignment="Left" Style="{StaticResource btnRaw}" Background="Transparent" BorderThickness="0" Height="17" Width="17" ToolTip="Tooltip" Click="DeleteLastEntry">
    <Grid>
        <TextBlock Grid.Column="0" Foreground="{StaticResource brushLayerstackCoherent}" VerticalAlignment="Center" HorizontalAlignment="Center" FontFamily="Segoe MDL2 Assets" FontSize="14.8" Text="&#xE91F;" />
        <TextBlock Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center" FontFamily="Segoe MDL2 Assets" FontSize="9" FontWeight="Bold" Text="&#xE738;" />
    </Grid>
</Button>

However, I want to do that NOT in xaml, but programatically in C#. I can create a button like this

Button myButton = new Button();
myButton.HorizontalAlignment = HorizontalAlignment.Left;
...

But how do I add the grid inside the button? An access via the Children-property is not present in myButton.

CodePudding user response:

     var button = new Button();

     var textBlock1 = new TextBlock();
     var textBlock2 = new TextBlock();

     var grid = new Grid();

     grid.Children.Add(textBlock1);
     grid.Children.Add(textBlock2);

     button.Content = grid;
  • Related