绑定控件不会在源更改时更新

时间:2021-06-03 00:58:55

标签: c# wpf

我绑定了这个属性

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

1 个答案:

答案 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";

     }
 }
相关问题