Reputation: 119
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
Upvotes: 3
Views: 10273
Reputation: 146
For your question, this seems to be the simplest.
txtCityName.Clear();
txtCityName.AppendText("Reset CityName");
binding is still maintained.
Upvotes: 0
Reputation: 1918
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}">
Upvotes: 7
Reputation: 169160
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
Upvotes: 0