Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 496
StormianRootSolver Avatar asked Jul 29 '11 06:07

StormianRootSolver


1 Answers

I was able to reproduce it for .NET 4.0 but it is not reproducible for the same application when you set .NET 3.5 framework in the preferences of project. In the case of .NET 4.0 - there are 2 calls for the getter if its type is FrameworkElement. But internal stacks are different. So it's definitely because of some internals of WPF 4.0. And well.. its quite hard to figure out why and how it works in this way. If time permits someone could investigate WPF internals with Reflector but I believe it's snowball's chance in hell :)

like image 110
Kreol Avatar answered Oct 17 '22 21:10

Kreol