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

前端 未结 3 1621
太阳男子
太阳男子 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:10

    Why dont you add a view model and keep your property there ?

    View Model class

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ComponentModel;
    
    namespace WpfApplication1
    {
        public class TestViewModel : INotifyPropertyChanged
        {
            public string _name2;
            public string Name2
            {
                get { return "_name2"; }
                set
                { 
                    _name2 = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("Name2"));
                }
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            public void OnPropertyChanged(PropertyChangedEventArgs e)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, e);
                }
            }
        }
    }
    

    EntitiesView User Control

    public partial class EntitiesView : UserControl
    {
    
        public EntitiesView()
        {
            InitializeComponent();
            this.DataContext = new TestViewModel();
        }
    }
    

提交回复
热议问题