How do I find what text had been added with TextChanged

后端 未结 2 953
醉话见心
醉话见心 2021-01-27 10:23

I\'m looking to synchronize between a text in the textbox and string in a variable. I found how to get the index in which the string was changed (in the textbox), the length add

2条回答
  •  一整个雨季
    2021-01-27 10:45

    DataBinding is the most common way in WPF to show and collect data in a UI

    Try this:

    
        
            
            
        
    
    

    Code for the window:

    public partial class MainWindow : Window
    {
        private readonly AViewModel viewModel = new AViewModel();
    
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = viewModel;
        }
    }
    

    And the code for the ViewModel that holds the data you want to show and collect:

    public class AViewModel : INotifyPropertyChanged
    {
        private string someText;
    
        public string SomeText
        {
            get
            {
                return someText;
            }
            set
            {
                if (Equals(this.someText, value))
                {
                    return;
                }
                this.someText = value;
                this.OnPropertyChanged();
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected void OnPropertyChanged(
            [CallerMemberName]string propertyName = null)
        {
            this.PropertyChanged?.Invoke(
                this,
                new PropertyChangedEventArgs(propertyName));
        }
    }
    

    Although this looks complicated for a simple scenario it has a lot of advantages:

    • You can write automated (unit)test for the ViewModel without creating a UI
    • Adding extra fields and logic is trivial
    • If the UI needs to change, the ViewModel will not always need to change

    The core of the mechanism is the {Binding ...} bit in the Xaml that tell WPF to synchronize the data between the Text property of the TextBox and the SomeText property of the object that is assigned to the DataContext. The other significant bits are: - in the constructor of the window the setting of the DataContext and - in the ViewModel the raising of the PropertyChanged event when the SomeText property changes so the binding will be notified.

    Note that this is just a basic example of DataBinding, there are many improvements that could be made in this code.

提交回复
热议问题