C# WPF 代码实现Binding时出现背景属性为NULL的问题排查
错误原因
- 绑定的
Source属性赋值错误:你当前把s.Background(也就是具体的Brush实例)作为绑定源,同时绑定路径设置为"Background",相当于WPF会尝试去Brush类中查找名为Background的属性,而Brush类本身不存在该属性,最终绑定失败拿到Null值。 - (可选优化)如果需要后续修改
Something类的Background属性时自动同步到UI,需要让Something类实现INotifyPropertyChanged接口,否则只有初始赋值生效,属性变更不会通知UI更新。
修正后的代码
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Something s = new Something(); Label testLabel = new() { Content = "TEST", Margin = new Thickness(5), Padding = new Thickness(5) }; Binding binding = new("Background"); // 正确:Source设为Something类的实例s,而不是s的Background属性值 binding.Source = s; testLabel.SetBinding(BackgroundProperty, binding); stackpanel.Children.Add(testLabel); } } // 如需支持属性变更通知,使用如下实现 public class Something : INotifyPropertyChanged { private Brush _background = Brushes.Green; public Brush Background { get { return _background; } set { _background = value; OnPropertyChanged(nameof(Background)); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
内容的提问来源于stack exchange,提问作者KaT_624
相关产品推荐
相关产品推荐

