绑定自定义依赖属性后仅初始更新,后续无更新问题排查
问题原因与解决方案
一、CustomButton的Background不更新的原因
你在Loaded事件里给Background绑定的Source直接赋值为Background2的当前实例(初始的米色画刷),而非绑定到Background2这个依赖属性本身。当Background2后续被设置为新的画刷对象时,绑定的Source仍指向最初的米色画刷,不会自动切换到新对象,因此Background不会跟着更新。
二、修正代码
修改CustomButton构造器中的绑定逻辑,将绑定源设为当前按钮实例,路径指向Background2依赖属性:
public CustomButton() { Loaded += (_, _) => { ClearValue(BackgroundProperty); SetBinding(BackgroundProperty, new Binding { Source = this, Path = new PropertyPath(nameof(Background2)), Mode = BindingMode.OneWay, }); }; }
调整后,绑定会监听Background2依赖属性的变化,每次Background2更新时,Background都会同步更新。
三、关于给Window添加DependencyProperty的实际需求
先纠正一个错误认知:WPF/UWP中的Window类直接继承自DependencyObject,你可以直接在Window子类中注册自定义依赖属性,无需额外注入继承DependencyObject的类。示例代码如下:
public sealed partial class MainWindow : Window { // 自定义依赖属性示例 public Brush CustomWindowBrush { get => (Brush)GetValue(CustomWindowBrushProperty); set => SetValue(CustomWindowBrushProperty, value); } public static readonly DependencyProperty CustomWindowBrushProperty = DependencyProperty.Register(nameof(CustomWindowBrush), typeof(Brush), typeof(MainWindow), new PropertyMetadata(new SolidColorBrush(Colors.White))); // 其余原有代码... }
在XAML中可直接绑定该属性:
<Grid Background="{x:Bind CustomWindowBrush, Mode=OneWay}"> <!-- 内容 --> </Grid>
内容的提问来源于stack exchange,提问作者appletree5641
相关产品推荐
相关产品推荐

