WPF Label to TextBox

后端 未结 5 1817
长情又很酷
长情又很酷 2021-01-18 11:39

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 p

5条回答
  •  情书的邮戳
    2021-01-18 12:10

    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

    
        
            
    
    

    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
    {
        /// 
        /// Interaction logic for LabelTextBox.xaml
        /// 
        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.

提交回复
热议问题