【问题标题】:What are the scenarios in which we need to use dependency property in WPF?我们需要在 WPF 中使用依赖属性的场景有哪些?
【发布时间】:2010-12-29 16:44:14
【问题描述】:

我们可以通过简单的CLR属性来实现绑定,那为什么还要使用DP呢?

【问题讨论】:

标签: wpf dependency-properties


【解决方案1】:

你什么时候需要DPs 而不是CLRPs?

  • 当你需要binding
  • 当你需要property value change callback(默认实现)
  • 当你需要property value validation
  • 当你需要animation
  • 当你需要property value inheritance
  • 当您需要attach a property value 到另一个元素时(附加属性,但仍然)
  • 当你需要styling

其中一些可以在CLR 属性中实现。但是,DPs 是小菜一碟。

【讨论】:

    【解决方案2】:

    通常这些在UserControls 和派生控件中声明。

    您可以将绑定到 CLR 属性,但不能将 CLR 属性绑定;你需要一个依赖属性来做任何绑定。

    编辑(回应评论)

    假设您需要一个 TextBox,但您想自定义它以在“EditMode”和“ReadMode”中具有不同的行为。您需要创建派生类或UserControl;无论哪种情况,您都将添加一个 DependencyPropery。

    public class TextBoxWithModes : TextBox
    {
        public bool EditMode
        {
            get { return (bool) GetValue(EditModeProperty); }
            set { SetValue(EditModeProperty, value); }
        }
    
        public static readonly DependencyProperty EditModeProperty = DependencyProperty.Register(
            "EditMode", typeof (bool), typeof (TextBoxWithModes));
    }
    

    有了这个,你可以在 XAML 中声明它:

    <Namespace:TextBoxWithModes Text="enter text here"
        Width="200"
        HorizontalAlignment="Center"
        EditMode="{Binding IsChecked, ElementName=editModeCheckBox}" />
    

    【讨论】:

    • 请给我一个更清楚的例子。
    猜你喜欢
    • 2016-09-28
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2023-03-19
    • 2013-01-08
    相关资源
    最近更新 更多