我正在尝试将代码内生成标签的背景属性设置为自定义对象属性。那么这段代码不起作用。标签显示正确,但背景属性为空值。我哪里错了?
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");
binding.Source = s.Background;
testLabel.SetBinding(BackgroundProperty, binding);
stackpanel.Children.Add(testLabel);
}
}
public class Something
{
private Brush _background = Brushes.Green;
public Brush Background
{
get { return _background; }
set { _background = value; }
}
}
答案 0 :(得分:0)
Binding 的来源是拥有绑定属性的对象,而不是属性的值。 如果您将其更改为:
binding.Source = s;
绑定将正确解析。