How to bind a simple string value to a text box?

前端 未结 3 1660
太阳男子
太阳男子 2021-01-16 11:36

I am using wpf. I want to bind a textbox with a simple string type value initialized in xaml.cs class. The TextBox isn\'t showing anything. Here is my XAML code

3条回答
  •  春和景丽
    2021-01-16 12:11

    You never set the value of your property. Simply defining set { _name2 = "abcdef"; } does not actually set the value of your property until you actually perform the set operation.

    You can change your code to look like this for it to work:

    public partial class EntitiesView : UserControl
    {
        private string _name2;
        public string Name2
        {
            get { return _name2; }
            set { _name2 = value; }
        }
    
        public EntitiesView()
        {
            Name2 = "abcdef";
            DataContext = this;
            InitializeComponent();
        }
    }
    

    Also, as people have mentioned, if you intend to modify your property's value later on and want the UI to reflect it, you'll need to implement the INotifyPropertyChanged interface:

    public partial class EntitiesView : UserControl, INotifyPropertyChanged
    {
        private string _name2;
        public string Name2
        {
            get { return _name2; }
            set
            {
                _name2 = value;
                RaisePropertyChanged("Name2");
            }
        }
    
        public EntitiesView()
        {
            Name2 = "abcdef";
            DataContext = this;
            InitializeComponent();
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        protected void RaisePropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

提交回复
热议问题