【问题标题】:WPF: DependencyProperty refusing to workWPF:DependencyProperty 拒绝工作
【发布时间】:2009-08-05 13:54:57
【问题描述】:

我试图在一个窗口上注册 3 个依赖属性来控制它的格式。我一遍又一遍地查看了代码,但我一定遗漏了一些东西。

public static readonly DependencyProperty TextColorProperty = DependencyProperty.Register("TextColor", typeof(Color), typeof(WinStickyFingers), new PropertyMetadata(Colors.White));
public Color TextColor {
    get { return (Color)base.GetValue(TextColorProperty); }
    set { base.SetValue(TextColorProperty, value); }
}

public static readonly DependencyProperty BackgroundColorProperty = DependencyProperty.Register("BackgroundColor", typeof(Color), typeof(WinStickyFingers), new PropertyMetadata(Colors.Black));
public Color BackgroundColor {
    get { return (Color)base.GetValue(BackgroundColorProperty); }
    set {
        base.SetValue(BackgroundColorProperty, value);
    }
}    
<TextBlock DockPanel.Dock="Top" Text="{Binding Name}" Foreground="{Binding TextColor,Converter={StaticResource DebugConverter}}" Background="{Binding Path=BackgroundColor}" />

我正在使用 Bea Stollnitz 的调试方法,但我的断点甚至没有被触发。

【问题讨论】:

    标签: wpf data-binding dependency-properties


    【解决方案1】:

    TextBlock 中的DataContext 是什么?它怎么知道它应该绑定到您的 Window 上的属性?

    您需要将DataContext 设置为Window 实例,或者在绑定上设置Source(或RelativeSource,或ElementName)属性。所有这些属性都作为解析Binding 的绑定对象的一种方式存在。 DataContext 是一个备用选项,如果其他都没有设置,但我猜你也没有设置。

    【讨论】:

    • 我的印象是最接近的顶层。开发 ASP.NET 污染了我的思想;)通过在父容器上设置 RelativeSource 解决了问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 2013-08-02
    • 2014-12-10
    相关资源
    最近更新 更多