2

I am using WPF forms and i want to know how to set TextBox.Text value though TextBox bind With MVVM. For Example: TextBox.Text = "Hello"; I want to set this value to Text box and my text box like

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        txtCityName.Text = "Hello Vaibhav";
        this.DataContext = new MyTesting();

    }
}

My WPF Window Form Class:

Next My Xaml:

 <Grid>
    <TextBox Name="txtCityName" Grid.Row="3" Grid.Column="1"   Text="{Binding CityName, UpdateSourceTrigger=PropertyChanged}" Height="40" Width="200"/>
</Grid>

And Next My Model:

internal class MyTesting : INotifyPropertyChanged
{
    private string _CityName;

    public MyTesting()
    {

    }
    public string CityName
    {
        get { return _CityName; }
        set { _CityName = value; OnPropertyChanged("CityName"); }
    }

    #region PropertyChangedEventHandler
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
    #region " RaisePropertyChanged Function "
    /// <summary>
    /// 
    /// </summary>
    /// <param name="propertyName"></param>
    private void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));

    }
    #endregion
}

But NULL assigned to TextBox . How to solve this

2 Answers2

7

Try this:

class AddressModel: INotifyPropertyChanged
{
        private string _cityName;
        public string CityName 
        {
        get {
              return _cityName; 
            }
        set {
              _cityName = value; 
              OnPropertyChanged("CityName");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string property)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
        }                           
}

And in your Code Behind:

AddressModel addressModel = new AddressModel();
addressModel.CityName = "YourCity";
this.dataContext = addressModel;

Xaml:

<TextBox Name="txtCityName" Grid.Row="3" Grid.Column="1" Text="{Binding CityName,UpdateSourceTrigger=PropertyChanged}">
tabby
  • 1,878
  • 1
  • 21
  • 39
0

txtCityName.Text = "YourCity" is not MVVM.

You should set the CityName source property instead of setting the Text property of the TextBox control.

<TextBox Name="txtCityName" Grid.Row="3" Grid.Column="1" Text="{Binding CityName}">

this.DataContext = new AddressModel();

AddressModel obj = this.DataContext as AddressModel;
obj.CityName = "..."; //<--this will update the data-bound TextBox
mm8
  • 163,881
  • 10
  • 57
  • 88