gpt4 book ai didi

wpf - 如何在 TextBox 与 WPF 中的 MVVM 绑定(bind)时设置 TextBox.Text 值

转载 作者:行者123 更新时间:2023-12-01 22:16:13 24 4
gpt4 key购买 nike

我正在使用 WPF 表单,我想知道如何通过 TextBox 与 MVVM 绑定(bind)来设置 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 。如何解决这个问题

最佳答案

试试这个:

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

关于wpf - 如何在 TextBox 与 WPF 中的 MVVM 绑定(bind)时设置 TextBox.Text 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45606844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com