WPF 中 TextBox 与 MVVM 绑定时如何设置 TextBox.Text 值

问题描述 投票:0回答:2

我正在使用 WPF 表单,我想知道如何通过 TextBox 与 MVVM 绑定来设置

TextBox.Text
值。 例如:
TextBox.Text = "Hello";
我想将此值设置为文本框,我的文本框如

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

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

    }
}

我的WPF窗口窗体类:

接下来我的 Xaml:

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

接下来是我的模型:

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
}

但是 NULL 分配给 TextBox 。怎么解决这个问题

wpf xaml
2个回答
7
投票

试试这个:

    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));
            }                           
    }

在你的代码隐藏中:

    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}">

0
投票

txtCityName.Text = "YourCity"
不是 MVVM。

您应该设置

CityName
源属性,而不是设置
Text
控件的
TextBox
属性。

<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
© www.soinside.com 2019 - 2024. All rights reserved.