开发者

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):

开发者_JAVA技巧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


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 :)


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜