WPF编程式绑定报错:ContentControl.Content需对象引用问题排查
WPF编程式数据绑定报错解决:访问ContentControl.Content需对象引用
我在极简WPF应用中尝试以编程方式创建简单的数据绑定,源为SourceClass实例的SourceText属性,目标为Button控件。相关代码如下:
namespace notify_on_source_updated { public class SourceClass { public string SourceText { get; set; } } /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Binding binding = new Binding("SourceText"); binding.Source = new SourceClass() { SourceText = "test" }; binding.NotifyOnSourceUpdated=true; btnAddInt.SetBinding(ContentControl.Content, binding); } } }
运行时出现错误:
访问非静态字段、方法或属性“ContentControl.Content”需要对象引用
我认为ContentControl.Content是正确的依赖属性,请问我哪里出错了?
错误原因与解决方法
问题出在依赖属性的引用方式上:ContentControl.Content是实例属性,直接用类名访问会触发“需要对象引用”的错误。WPF中,所有依赖属性都对应一个静态的[PropertyName]Property字段,这才是编程式绑定中指定目标属性的正确标识符。
把绑定代码的最后一行修改为:
btnAddInt.SetBinding(ContentControl.ContentProperty, binding);
额外提示
你的SourceClass没有实现INotifyPropertyChanged接口,虽然初始化时能显示"test",但后续修改SourceText的值不会自动更新Button的内容。如果需要属性变更自动同步,记得给SourceClass实现该接口:
public class SourceClass : INotifyPropertyChanged { private string _sourceText; public string SourceText { get => _sourceText; set { _sourceText = value; OnPropertyChanged(nameof(SourceText)); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
内容的提问来源于stack exchange,提问作者user32882
相关产品推荐
相关产品推荐

