WPFwiki, wpf, wiki, .net 3.0, windows presentation foundation, FAQ, free resources, solution, development, microsoft Home of the world's largest WPF FAQ
Edit

Category

Fundamentals

Edit

Question

How do I create a read-only DependencyProperty?

Edit

Answer

Creating a read-only property is very much similar to creating a regular DependencyProperty.

Refer to the related links for details on creating dependency properties.

When declaring a read-only property, the return value of the DependencyProperty.RegisterReadOnly() method is a DependencyPropertyKey instead of the DependencyProperty returned by the DependencyProperty.Register() function.

The DependencyPropertyKey should be stored in a private static readonly or protected static readonly field (as opposed to regular dependency properties, which should be public static readonly fields). This is because one could modify the value of the read-only property by accessing its DependencyPropertyKey.

Instead, you should declare another DependencyProperty field (public static readonly) and assign to it the DependencyPropertyKey.DependencyProperty property.

This property contains the read-only DependencyProperty which can then be used by class users.

Inside your class, you can then use the DependencyPropertyKey when changes are needed on the read-only property.

Example:

public CustomClass1 : DependencyObject
{
    #region 'ReadonlyProp' dependency property

private static readonly DependencyPropertyKey ReadonlyPropKey = DependencyProperty.RegisterReadOnly( "ReadonlyProp", typeof(int), typeof(CustomClass1), new PropertyMetadata());

public static readonly DependencyProperty ReadonlyPropProperty = ReadonlyPropKey.DependencyProperty;

public int ReadonlyProp{ get { return (int)GetValue(ReadonlyPropProperty); } private set { SetValue(ReadonlyPropKey, value); } }

#endregion }


Edit

Related Links

How to declare a dependency property

Edit

Resources

philippine travel, travel asia, mayweather vs ortiz tickets, mayweather vs ortiz, pacquiao vs marquez, mayweather vs ortiz live streaming, pacquiao vs marquez tickets, pacquiao vs marquez, hopkins vs dawson, hopkins vs dawson live streaming, donaire vs narvaez, donaire vs narvaez tickets, cotto vs margarito, cotto vs margarito tickets, st-Pierre vs diaz, st-Pierre vs diaz tickets, fifa world cup

All content is Copyright ©2007 Xceed Software Inc. unless otherwise indicated. See the Terms of Service. Contributors must read and agree to the Contribution Policy. WPFwiki is brought to you by Xceed, makers of the powerful yet free Xceed DataGrid for WPF.