4
\$\begingroup\$

I want to put some text next to its label (both of which are text blocks - which are faster than labels as I understand it). The best way I've found for doing this is a stack panel.

I have (repeated 3 times in a control) code like:

    <StackPanel  Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2" Orientation="Horizontal">
        <TextBlock Text="Start:" FontWeight="DemiBold" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
        <TextBlock  Text="12:00pm"  VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="5,0"/>
    </StackPanel>

Is this the cleanest way to do this, or is there a better control? I was kind of thinking about making a wrapper control around the stack panel, but then I would just end up with:

    <LabeledTextBlock Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2">
<LabledTextBlock.Label>
        <TextBlock Text="Start:" FontWeight="DemiBold" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
</LabledTextBlock.Label>
        <TextBlock  Text="12:00pm"  VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="5,0"/>
    </LabeledTextBlock >

I guess I could refine it more:

<LabeledContent Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2" Label="Start" Content="12:00pm"/>

Simplicity at the cost of flexibility. Perhaps instead I should be doing it as a style?

\$\endgroup\$
  • \$\begingroup\$ Should this be a stackoverflow question? \$\endgroup\$ – RayLoveless Sep 7 '18 at 21:16
3
\$\begingroup\$

My opinion is that for simple tasks like in your situation, you should not complicate your XAML. Wrapping a StackPanel around two TextBlock-elements is still pretty clean.

Extracting the code and wrapping it in your own control where you would set the Label and Content surely is an option. But if this only to be done once, I think you're overdoing it. Only when you have to place the same code there a lot of times, your XAML will be cleaner using your own control.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.