TextBlock中的绑定在WPF中不起作用

我想在我的类中动态更改TextBlock文本。

XAML代码

  

C#

 string footerMainMenuText = "Setting"; Binding set = new Binding(""); set.Mode = BindingMode.OneWay; set.Source = footerMainMenuText; Footer_text.DataContext = footerMainMenuText; Footer_text.SetBinding(TextBlock.TextProperty, set); 

我检查了最后一行,并正确设置了Footer_text.Text 。 ( Footer_text.Text="Setting" ),但我的应用程序中的TextBlock没有显示“Setting”。 这里有什么问题?

如果你有约束力 – 为什么不在XAML中呢? 看看你的代码,这是毫无意义的 – 你也可以去吧

 Footer_text.Text = "Setting"; 

理想情况下,您应该在XAML中执行此操作,或者至少为其提供绑定的内容

  

我不确定为什么你会把它自己的’string’绑定到任何东西……你有一个你需要绑定到text属性的对象吗?

也用

 Binding("") 

那是做什么的? 一条空白路径? 不确定绑定目标会在那里……你试过吗?

 Binding() 

代替?

编辑:

您的绑定未更新控件的原因可能是因为您尚未绑定到实现INotifyPropertyChanged或类似接口的对象。 控件需要知道值何时发生了变化,所以我认为绑定到’string’并不会在TextBlock发生变化时给出正确的通知

编辑2:

以下是绑定工作的快速示例:

我的窗口类Window.cs:

          

Window.xaml.cs中的代码

 public partial class MainWindow : Window { SomeObjectClass obj = new SomeObjectClass(); public MainWindow() { InitializeComponent(); txtName.DataContext = obj; } private void Button_Click(object sender, RoutedEventArgs e) { obj.Name = "Hello World"; } private void Button_Click_1(object sender, RoutedEventArgs e) { obj.Name = "Goobye World"; } } 

要绑定的对象(使用INotifyPropertyChanged)

 class SomeObjectClass : INotifyPropertyChanged { private string _name = "hello"; public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string PropertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(PropertyName)); } } 

单击按钮更改SomeObject.Name,但它会更新文本框。