Databinding phenomenon in WPF (binding to a FrameworkElement) - any ideas why?

Viewed 843

In an application of mine (this has to do with very dynamic navigation and content presentation) I have to use this construct in XAML:

<ContentControl Content={Binding ContentElement} />

So far, so good. This is great, absolutely great. I can host arbitrary stuff all over the place.

But there seems to be a strange, well, lets call it "phenomenon" in WPF (I believe it is in the BindingMarkupExtension, but not sure yet):

When my ContentElement property looks like this:

public FrameworkElement ContentElement
{
    get
    {
        return this.m_ContentElement;
    }
}

then the getter gets called TWICE (!!!) for each databinding operation (this includes when the user changes the language on the fly or reloads the hosting control).

However (and this is what is REALLY mind boggling for me):

When I change my ContentElement property to:

public object ContentElement
{
    get
    {
        return this.m_ContentElement;
    }
}

then the getter gets called once. Seriously, I'm not lying here. It is absolutely reproducible in the simplest applications, you can try for example by returning a new "TextBlock" (thats what I usually do to test or learn about more advanced WPF concepts).

Any ideas why?

The reason why I ask is that I hate the following consequences of the solution:

  • I lose type safety at this point
  • This may be a bit hard to explain to new developers or overly sceptical wisecracks
2 Answers

I had the same Problem and found an answer from Microsoft in another forum: http://connect.microsoft.com/VisualStudio/feedback/details/554237/problem-binding-image-property-called-twice-for-each-item

As Kreol said, it is interesting to see that this was done in the .NET 4.0.

I don't know what to think about it. It certainly is done on purpose, to improve the performances or something.

In our case, we have a property that return a view of our model, and this view will be displayed in differents screens, so we can't implement a single field with a

if (_localValue != null)

statement, and must create a new Control everytime the property is getted. So this may not be so performant anymore.

Any other thoughts?

Related