我绑定了这个属性
private string _attributeName = "";
public string AttributeName
{
get => _attributeName;
set
{
_attributeName = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
带有 TextBox
<TextBox Name="tbAttributeName" Text="{Binding ElementName=_this, Path=AttributeName}"/>
当我在此 TextBox
中输入文本时,它会更改 AttributeName,但是当我尝试通过 CodeBehind 更改 AttributeName 时,TextBox
不会更改。
AttributeName = "name" //Won't change the TextBox.Text
答案 0 :(得分:2)
您必须将 DataContext 设置为您的窗口,您可以在构造函数中进行如下操作
public MainWindow()
{
InitializeComponent();
DataContext = this; // set the code beind class to be the datacontext source for xaml
}
并在 xaml 中绑定您的属性,如下所示
<TextBox Name="tbAttributeName" Text="{Binding AttributeName}"></TextBox>
确保您的窗口实现了 INotifyPropertyChanged
所以后面的代码看起来像这样
public partial class MainWindow : Window ,INotifyPropertyChanged // <<<<<<<<
{
public MainWindow()
{
InitializeComponent();
DataContext = this; // <<<<<<<<<<<<<<
}
private string _attributeName = "";
public string AttributeName
{
get => _attributeName;
set
{
_attributeName = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private void btn_Click(object sender, RoutedEventArgs e)
{
AttributeName = "value changerd";
}
}