Question

I've put together a WPF application using ObservableCollection and Dependency Properties which is cool because I just have to add an item to the ObservableCollection and it shows up automatically, e.g. I display the objects in the collection as boxes on the screen in a wrappanel, each box showing its Title.

So then I wanted to have each item show not only its Title plus a prefix or suffix, but the Dependency Object property doesn't even seem to be used. I can put a break point on it and it is never reached.

Can anyone enlighten me why, if I add text to my outgoing property, that that text is never seen? I have read that the value is actually "stored not in the object but in WPF" but I don't understand what that means.

Why is the text this text will NOT be seen never output by the dependency object?

public class ApplicationItem : DependencyObject
{

    public string Title
    {
        get
        {
            return (string)GetValue("this text will NOT be seen: " + TitleProperty);
        }
        set
        {
            SetValue(TitleProperty, "this text will be seen: " + value);
        }
    }
}
Was it helpful?

Solution

TitleProperty is not a normal property but a dependency property so if you want to retrieve the value of your TitleProperty you have to do :

var title = (string)GetValue(TitleProperty);

In WPF guideline, the public property to access a Dependency Property is not called by WPF and the binding engine (not necessary). This public property is only used by your code behind. So you MUST not add code logic inside your public property.

But you can use a FrameworkPropertyMetadata when you register your DP and provide a CoerceValueCallback to change the setted value.

You can also use a IValueConverter with your binding.

OTHER TIPS

I got this to work for me:

public string Title
{
    get 
    { 
        string value = (string)GetValue(TitleProperty); 
        return value + " postfix";
    }
    set 
    { 
        SetValue(TitleProperty, "Prefix " + value); 
    }
}

Is there a reason why you are attempting to modify the value when retrieving it rather than just modifying it when the value is set?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top