我在谷歌上搜索了关于如何开始使用WPF / Silverlight中的依赖属性,但对依赖属性没有任何想法,有人能从初学者的角度告诉我吗,这样我就可以了解一些关于它的知识并在我的项目中使用它。
提前感谢。
有人能给我一个链接或简单应用程序的代码示例,以简单的方式解释什么是依赖属性吗?非常感激。
我在谷歌上搜索了关于如何开始使用WPF / Silverlight中的依赖属性,但对依赖属性没有任何想法,有人能从初学者的角度告诉我吗,这样我就可以了解一些关于它的知识并在我的项目中使用它。
提前感谢。
有人能给我一个链接或简单应用程序的代码示例,以简单的方式解释什么是依赖属性吗?非常感激。
我发现实现一个DependencyProperty通常涉及四个部分:
您可以将依赖属性添加到UserControl中,以便您可以将其数据绑定到UserControl实例化的DataContext中的某些内容。例如,您可以向SoUserControl添加一个属性:
#region SampleProperty // Demo for SO 2424526
public static readonly DependencyProperty SamplePropertyProperty
= DependencyProperty.Register("SampleProperty", typeof(int), typeof(SoUserControl), new PropertyMetadata(OnSamplePropertyChanged));
/// <summary>
/// Demo for SO 2424526
/// Gets or sets dependency property.
/// </summary>
public int SampleProperty
{
get { return (int)GetValue(SamplePropertyProperty); }
set { SetValue(SamplePropertyProperty, value); }
}
/// <summary>
/// Handld changes to SamplePropertyProperty by calling a handler in the associated object.
/// </summary>
/// <param name="obj">object the property is associated with</param>
/// <param name="e">details of change</param>
static void OnSamplePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
(obj as SoUserControl).OnSamplePropertyChanged(e);
}
/// <summary>
/// Handle changes to the SamplePropertyProperty dependency property.
/// </summary>
/// <param name="e">details of change</param>
private void OnSamplePropertyChanged(DependencyPropertyChangedEventArgs e)
{
int SamplePropertyNewValue = (int)e.NewValue;
// do something with the internal logic of the control
}
#endregion
我认为你可以将其与关键字yield进行比较。 它允许您生成一个惰性列表或无限的生成器。 每次需要该列表中的一个项目时,都会从该列表中请求一个项目,并且代码将继续流程。
依赖属性与值或内容相同。它根据它所依赖的其他值惰性地计算所需值。 它可以缓存值,并且当底层部分“脏”(即有变更)时,它将传播--使所有依赖于它的级别无效。
对象需要具备DependencyObject的功能才能参与其中(也就是说,这样引擎才能知道它并将其介绍给该链)。
机制是通用和不固定的,没有仅符合一个接口。 但它比我说的还要复杂一些。
我在以下博客文章中找到了一个很好的解释,以加强我的理解: http://blog.hackedbrain.com/2004/12/04/understanding-dependencyobject-and-dependencyproperty/
首先,你应该阅读一本书。
我已经阅读了 Manning 出版社的《WPF In Action With Visual Studio 2005》。
作为对我刚才所接收到的否定标点符号的回答,依赖属性是 WPF 的一部分,没有基础知识就无法理解依赖属性。
因此,我认为仅仅理解什么是依赖属性是浪费时间的,因为我担心最终会错误地使用它。
另外,MSDN 网站提供有关 WPF 和依赖属性的免费信息。