7

I am wondering, which is the best and quickest way to get the well known Label Input [or output, doesn't matter] combination in WPF. Its a simple Task, just think of a quick output of the "object" ME:


Name - Christian

Age - 28

Mood - Good


I know, I can use a Grid with TextBlocks. But to be honest, the "short" XAML for this is nearly half a page long (RowDefinitions, ColDefs, Grid.Col on each Label)

The alternative way, using three StackPanels (horizontal) with one vertical seems also a little bit stupid. In this case, I have to give each Label a fixed width, to get the indent correct. And it just does not "feel" right.

So, given the Situation above, you got a custom object with 3-6 Properties you just want to dump as readonly to your GUI, how would you do it (in WPF, Silverlight too, if you are really in the mood :).

I can, of course, write a usercontrol for this. But why reinvent the wheel, if it might be already there...

And finally, to illustrate even further, the example I just created in real life and was the reason for this post:

      <StackPanel>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Log Count"  Width="100"/>
            <TextBlock Text="{Binding LastLogRun.LogMessageCount}"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Start Time" Width="100"/>
            <TextBlock Text="{Binding LastLogRun.StartTime}"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="End Time" Width="100"/>
            <TextBlock Text="{Binding LastLogRun.EndTime}"/>
        </StackPanel>
    </StackPanel>
3
  • You seem to be asking for two things "best/best-practices" and "quickest/quick output/dump". Which one do you want? Bryan A. gives you a quick solution, and Joe W. gives you a good formatting solution which you dismiss in your question...
    – micahtan
    Jun 19, 2009 at 5:31
  • Yeah, you are right, was not the best question ever. I think the Bryan A. Answer is as short as it will get, I like it for real quick and dirty stuff without formatting. The user control approach is also very nice, perhaps it gets voted up a little bit. Thanks all for your ideas... Jun 19, 2009 at 10:26
  • Personally I tend to use Grids for this but you seemed to be asking for shortest XAML. If you're going to be doing it a lot or you want to increase performance I would make a User Control using a ListView or ListBox. Jun 19, 2009 at 13:55

5 Answers 5

2

You could use shared size groups to get the auto-sizing Grid behavior of two nicely-lined-up columns, while still being able to pull out the complexity into a UserControl.

Here's an example of using a LabeledEdit control that would do what you're looking for. The complexity has all been factored away into the UserControl, and all you need to do is remember to set Grid.IsSharedSizeScope on the StackPanel:

<Window x:Class="WpfApplication5.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication5"
        Name="Self" Title="Window1" Height="300" Width="300">
    <StackPanel Grid.IsSharedSizeScope="True">
        <local:LabeledEdit Label="Name"/>
        <local:LabeledEdit Label="Age" Text="28"/>
        <!-- and with databinding... -->
        <local:LabeledEdit Label="Width"
                           Text="{Binding Width, ElementName=Self}"/>
        <local:LabeledEdit Label="Height"
                           Text="{Binding Height, ElementName=Self}"/>
    </StackPanel>
</Window>

And here's the source code for the UserControl. LabeledEdit.xaml:

<UserControl x:Class="WpfApplication5.LabeledEdit"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Name="Self">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" SharedSizeGroup="LabeledEdit_Labels"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Label Grid.Column="0" Content="{Binding Label, ElementName=Self}"/>
        <TextBox Grid.Column="1" Text="{Binding Text, ElementName=Self}"/>
    </Grid>
</UserControl>

LabeledEdit.xaml.cs:

using System.Windows;

namespace WpfApplication5
{
    public partial class LabeledEdit
    {
        public static readonly DependencyProperty LabelProperty =
            DependencyProperty.Register("Label", typeof(object), typeof(LabeledEdit));
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(LabeledEdit),
            new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

        public LabeledEdit()
        {
            InitializeComponent();
        }

        public object Label
        {
            get { return GetValue(LabelProperty); }
            set { SetValue(LabelProperty, value); }
        }
        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }
    }
}
1

If you're using 3.5sp1 you can use StringFormat in the binding. Something like this should work...

<TextBlock Text="{Binding LastLogRun.LogMessageCount, StringFormat={}Log Count - {0}}" />
0

Perhaps you should rethink your UI. Why would you want Label - Textbox on the same line? That's a horrendous waste of space.

Why not Label over texbox? Then you've got a simple UI and simple XAML:

<StackPanel Orientation="Vertical">
  <TextBlock>Name</TextBlock>
  <TextBox />
  <TextBlock>Age</TextBlock>
  <TextBox />
  <TextBlock>Mood</TextBlock>
  <TextBox />
</StackPanel>

Add some styling for your TextBlocks and you've got a nice, clean UI, with very little repetition.

2
  • Why are you accusing OP of wasting screen space, when your approach wastes far more? Think about it: with OP's approach, a "Name" label takes up 42x26 = 1092 pixels. With your approach, that same label is the full width of the screen, so on my monitor, even if I give you a head start by setting Padding=0, yours takes 1440x16 = 23040 pixels. Your layout is a legitimate option, but don't kid yourself that it's less wasteful of real estate.
    – Joe White
    Jun 18, 2009 at 22:21
  • 1
    Randolpho's solution is good, not because it uses less screen space, but because it is easier to internationalize. By putting the Label above the TextBox, the spacing does change and the length of the labels change for different languages. Jun 18, 2009 at 22:48
0

The silverlight toolkit has a DataForm control that works pretty cool!

0

I know this is 13! years later, but, if anyone else is curious, you can use BulletDecorator (docs). There's special handling for vertical alignment based on the first line of text, if the content is text-based content.

OP's example, written with BulletDecorators:

<StackPanel>
  <BulletDecorator>
    <BulletDecorator.Bullet>
      <TextBlock Text="Log Count" Width="100"/>
    </BulletDecorator.Bullet>
    <TextBlock Text="{Binding LastLogRun.LogMessageCount}"/>
  </BulletDecorator>
  <BulletDecorator>
    <BulletDecorator.Bullet>
      <TextBlock Text="Start Time" Width="100"/>
    </BulletDecorator.Bullet>
    <TextBlock Text="{Binding LastLogRun.StartTime}"/>
  </BulletDecorator>
  <BulletDecorator>
    <BulletDecorator.Bullet>
      <TextBlock Text="End Time" Width="100"/>
    </BulletDecorator.Bullet>
    <TextBlock Text="{Binding LastLogRun.EndTime}"/>
  </BulletDecorator>
</StackPanel>

If you're not a fan of that 👆 syntax (it's a bit verbose for my sake), you can use some attached properties to clean it up some.

BulletHelper.cs

public static class BulletHelper
{
    #region Bullet

    public static readonly DependencyProperty BulletProperty = DependencyProperty.RegisterAttached(
        "Bullet",
        typeof(object),
        typeof(BulletHelper),
        new FrameworkPropertyMetadata(OnBulletChanged)
    );

    public static object? GetBullet(DependencyObject target)
        => target.GetValue(BulletHelper.BulletProperty);

    public static void SetBullet(DependencyObject target, object? value)
        => target.SetValue(BulletHelper.BulletProperty, value);

    private static void OnBulletChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is BulletDecorator bulletDecorator)
        {
            bulletDecorator.Bullet = CreateUiElement(e.NewValue);
        }
    }

    #endregion Bullet

    #region Child

    public static readonly DependencyProperty ChildProperty = DependencyProperty.RegisterAttached(
        "Child",
        typeof(object),
        typeof(BulletHelper),
        new FrameworkPropertyMetadata(OnChildChanged)
    );

    public static object? GetChild(DependencyObject target)
        => target.GetValue(BulletHelper.ChildProperty);

    public static void SetChild(DependencyObject target, object? value)
        => target.SetValue(BulletHelper.ChildProperty, value);

    private static void OnChildChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is BulletDecorator bulletDecorator)
        {
            bulletDecorator.Child = CreateUiElement(e.NewValue);
        }
    }

    #endregion Child

    [return: NotNullIfNotNull("value")]
    private static UIElement? CreateUiElement(this object? value)
    {
        return value switch
        {
            null => null,

            // Uncomment if using MaterialDesignThemes (https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit)
            // PackIconKind kind => new PackIcon { Kind = kind },


            // Uncomment if using FontAwesome6.Svg (https://github.com/MartinTopfstedt/FontAwesome6)
            // EFontAwesomeIcon.None => null,
            // EFontAwesomeIcon fontAwesomeIcon => new SvgAwesome { Icon = fontAwesomeIcon },


            UIElement uiElement => uiElement,
            _ => new ContentPresenter { Content = value },
        };
    }
}

The above attached properties reduces it to:

<StackPanel>
  <BulletDecorator BulletHelper.Bullet="Log Count"
                   BulletHelper.Child="{Binding LastLogRun.LogMessageCount}" />
  <BulletDecorator BulletHelper.Bullet="Start Time"
                   BulletHelper.Child="{Binding LastLogRun.StartTime}" />
  <BulletDecorator BulletHelper.Bullet="End Time"
                   BulletHelper.Child="{Binding LastLogRun.EndTime}" />
</StackPanel>

Unfortunately, you lose out on the Width property that was previously set on the TextBlock.


I wish BulletDecorator was easier to work with. Unfortunately, its two main properties, Child and Bullet, are not dependency properties, and they both must be UIElement.

However. You can make a Control (not a UserControl!) that makes BulletDecorator easier to use.

BulletControl.cs

public class BulletControl : ContentControl
{
    static BulletControl()
    {
        FocusableProperty.OverrideMetadata(typeof(Control), new FrameworkPropertyMetadata(false));
        DefaultStyleKeyProperty.OverrideMetadata(typeof(BulletControl), new FrameworkPropertyMetadata(typeof(BulletControl)));
    }


    #region Bullet

    public static readonly DependencyProperty BulletProperty = DependencyProperty.Register(
        nameof(Bullet),
        typeof(object),
        typeof(BulletControl),
        new FrameworkPropertyMetadata(BulletChangedCallback)
    );

    public object? Bullet
    {
        get => this.GetValue(BulletProperty);
        set => this.SetValue(BulletProperty, value);
    }

    private static void BulletChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is Bullet ctrl)
        {
            ctrl.SetValue(HasBulletPropertyKey, e.NewValue is not null);
        }
    }

    #endregion Bullet

    #region BulletStringFormat

    public static readonly DependencyProperty BulletStringFormatProperty = DependencyProperty.Register(
        nameof(BulletStringFormat),
        typeof(string),
        typeof(BulletControl),
        new FrameworkPropertyMetadata()
    );

    public string? BulletStringFormat
    {
        get => (string?)this.GetValue(BulletStringFormatProperty);
        set => this.SetValue(BulletStringFormatProperty, value);
    }


    #endregion BulletStringFormat

    #region BulletTemplate

    public static readonly DependencyProperty BulletTemplateProperty = DependencyProperty.Register(
        nameof(BulletTemplate),
        typeof(DataTemplate),
        typeof(BulletControl),
        new FrameworkPropertyMetadata()
    );

    public DataTemplate? BulletTemplate
    {
        get => (DataTemplate?)this.GetValue(BulletTemplateProperty);
        set => this.SetValue(BulletTemplateProperty, value);
    }

    #endregion BulletTemplate

    #region BulletTemplateSelector

    public static readonly DependencyProperty BulletTemplateSelectorProperty = DependencyProperty.Register(
        nameof(BulletTemplateSelector),
        typeof(DataTemplateSelector),
        typeof(BulletControl),
        new FrameworkPropertyMetadata()
    );

    public DataTemplateSelector? BulletTemplateSelector
    {
        get => (DataTemplateSelector?)this.GetValue(BulletTemplateSelectorProperty);
        set => this.SetValue(BulletTemplateSelectorProperty, value);
    }

    #endregion BulletTemplateSelector

    #region HasBullet

    private static readonly DependencyPropertyKey HasBulletPropertyKey = DependencyProperty.RegisterReadOnly(
        name: nameof(HasBullet),
        propertyType: typeof(bool),
        ownerType: typeof(BulletControl),
        typeMetadata: new FrameworkPropertyMetadata()
    );

    public bool HasBullet
    {
        get => (bool)this.GetValue(HasBulletPropertyKey.DependencyProperty);
        private set => this.SetValue(HasBulletPropertyKey, value);
    }

    #endregion HasBullet
}

Generic.xaml

    <Style TargetType="{x:Type controls:BulletControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type controls:BulletControl}">
                    <BulletDecorator>
                        <BulletDecorator.Bullet>
                            <ContentPresenter ContentSource="Bullet" />
                        </BulletDecorator.Bullet>
                        <ContentPresenter ContentSource="Content" />
                    </BulletDecorator>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

With 👆, the OP's sample code becomes:



<StackPanel>
  <StackPanel.Resources>
    <DataTemplate x:Key="BulletTemplate">
      <TextBlock Text="{Binding}" 
                 Width="100" />
    </DataTemplate>
  </StackPanel.Resources>

  <BulletControl Bullet="Log Count"
                 Content="{Binding LastLogRun.LogMessageCount}"
                 BulletTemplate="{StaticResource BulletTemplate}"
                 />
  <BulletControl Bullet="Start Time"
                 Content="{Binding LastLogRun.StartTime}" 
                 BulletTemplate="{StaticResource BulletTemplate}"
                 />
  <BulletControl Bullet="End Time"
                 Content="{Binding LastLogRun.EndTime}"
                 BulletTemplate="{StaticResource BulletTemplate}"
                 />
</StackPanel>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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