wpfxaml

How to Set TextBox.Text Value while TextBox bind with MVVM in WPF


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


Solution

  • 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