Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to: Override Metadata for a Dependency Property

Tags:

wpf

how to override default dependency property metadata. for example ;Text property for textbox. i use this code

           class UCTextBox : TextBox
       {
           public UCTextBox()
        {
       var defaultMetadata = TextBox.TextProperty.GetMetadata(typeof(TextBox));

       TextBox.TextProperty.OverrideMetadata(typeof(UCTextBox),
     new          FrameworkPropertyMetadata(string.Empty,
        FrameworkPropertyMetadataOptions.Journal | 
     FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
        defaultMetadata.PropertyChangedCallback,
        new CoerceValueCallback(CoerceText)
        )); 
}

    private static object CoerceText(DependencyObject d, object value)
     {
     return   value.ToString().Replace(",","");           
    }

but this In both runs(get,set)

No one can help me!!!:(((

like image 664
ar.gorgin Avatar asked Oct 01 '11 05:10

ar.gorgin


People also ask

Why is dependency property static?

DependencyProperty has to be static (Class level) because when we create multiple objects of the class which has that property and want to refer the default value for that property the value has to come from that static instance of DependencyProperty.

What is property metadata?

Property metadata can be defined and used during dependency property registration when calling the Register method (or variations for attached properties or read-only dependency properties), or after original owner registration when calling the OverrideMetadata method. AddOwner also takes property metadata.

What is the biggest feature of dependency property?

Arguably the biggest feature of a dependency property is its built-in ability to provide change notification. The motivation for adding such intelligence to properties is to enable rich functionality directly from declarative markup.


1 Answers

Here is an example of a class derived from TextBox overriding the metadata for the Text property:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

public class MyTextBox : TextBox
{
    static MyTextBox()
    {
        TextBox.TextProperty.OverrideMetadata(typeof(MyTextBox),
            new FrameworkPropertyMetadata(string.Empty,
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault |
                FrameworkPropertyMetadataOptions.Journal,
                null, /* property changed callback */
                null, /* coerce value callback */
                true, /* is animation prohibited */
                UpdateSourceTrigger.LostFocus));
    }
}

Notice that the override is place in the static constructor, not the ordinary constructor.

like image 77
Rick Sladkey Avatar answered Nov 15 '22 08:11

Rick Sladkey