C# – WPF Label to TextBox

cnetwpf

what is the best practice to show text label (e.g. "Name") with the TextBox in WPF?
I want a label "Name" above the TextBox and many similar Labels/TextBoxes.
Should I put the pairs Label/TextBox into the vertical StackPanel?

Is there a simpler solution?

Best Answer

It really depends on what you want to do with these controls in the future. If you want to reuse this kind of control multiple times (and maybe create it on the fly), it would be the best to create UserControl and program it. You can then easily reuse it in a very simple manner (like putting in on StackPanel).

Code for LabelTextBox.xaml

<UserControl x:Class="YourProject.LabelTextBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="49" d:DesignWidth="314" MinHeight="49" MaxHeight="49">
    <Grid>
        <Label Content="Label" Height="28" HorizontalAlignment="Left" Name="BaseLabel" VerticalAlignment="Top" />
        <TextBox Height="23" Margin="0,26,0,0" Name="BaseTextBox" VerticalAlignment="Top" />
    </Grid>
</UserControl>

Code for LabelTextBox.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace YourProject
{
    /// <summary>
    /// Interaction logic for LabelTextBox.xaml
    /// </summary>
    public partial class LabelTextBox : UserControl
    {
        public LabelTextBox()
        {
            InitializeComponent();
        }



        string LocalLabel = "";
        string LocalTextBox = "";

        public string Label
        {
            get { return LocalLabel; }
            set
            {
                LocalLabel = value;
                BaseLabel.Content = value;
            }
        }

        public string TextBox
        {
            get { return LocalTextBox; }
            set
            {
                LocalTextBox = value;
                BaseTextBox.Text = value;
            }
        }
    }
}

You can change Label text and TextBox content with Label and TextBox property of new control (hidden in "Other" part of Properties in designer. You can also program additional functions for the UserControl.

If you don't need to reuse these controls so much, other solutions will suffice.