代码之家  ›  专栏  ›  技术社区  ›  Jiew Meng

设置程序不在依赖属性上运行?

  •  36
  • Jiew Meng  · 技术社区  · 14 年前

    只是一个简短的问题,澄清一些疑问。元素绑定到依赖属性时是否不运行setter?

    public string TextContent
    {
        get { return (string)GetValue(TextContentProperty); }
        set { SetValue(TextContentProperty, value); Debug.WriteLine("Setting value of TextContent: " + value); }
    }
    
    public static readonly DependencyProperty TextContentProperty =
        DependencyProperty.Register("TextContent", typeof(string), typeof(MarkdownEditor), new UIPropertyMetadata(""));
    

    <TextBox Text="{Binding TextContent}" />
    

    正如我注意到的,下面我的设定器不运行

    Debug.WriteLine("Setting value of TextContent: " + value);
    
    2 回复  |  直到 14 年前
        1
  •  49
  •   Dean Chalk    14 年前

    WPF绑定引擎调用 GetValue SetValue 直接(绕过属性设置器和getter)。您需要该属性在那里,以便在XAML标记中支持它(并正确编译)。

        2
  •  39
  •   Kishore Kumar    14 年前

    若要创建DependencyProperty,请向类型中添加DependencyProperty类型的静态字段,并调用DependencyProperty.Register()创建Dependency属性的实例。DependentyProperty的名称必须始终以…属性结尾。这是WPF中的命名约定。

    要使它可以作为普通的.NET属性访问,您需要添加一个属性包装器。此包装器只通过使用从DependencyObject继承的getValue()和setValue()方法并将DependencyProperty作为键传递,在内部获取和设置值。

    不要向这些属性添加任何逻辑,因为只有在从代码设置属性时才调用这些逻辑。如果从XAML设置属性,则直接调用setValue()方法。

    每个DependencyProperty都为更改通知、值强制和验证提供回调。这些回调是在依赖属性上注册的。

    资料来源: http://www.wpftutorial.net/DependencyProperties.html