ContentPresenter Visibility binding inside Grid not working?

≡放荡痞女 提交于 2019-12-05 12:49:38
Gedde

This is because it does not work to bind visibility with a converter on the ContentPresenter element.

If you change the ContentPresenter to a ContentControl it will work to bind the visibility property with a converter, and then you don't have to nest it within another element.

This is apparently because ContentPresenter is a light weight element that is meant to be used within a ControlTemplate.

From MSDN (with my highlighting):

You typically use the ContentPresenter in the ControlTemplate of a ContentControl to specify where the content is to be added. Every ContentControl type has a ContentPresenter in its default ControlTemplate.

When a ContentPresenter object is in a ControlTemplate of a ContentControl, the Content, ContentTemplate, and ContentTemplateSelector properties get their values from the properties of the same names of the ContentControl. You can have the ContentPresenter property get the values of these properties from other properties of the templated parent by setting the ContentSource property or binding to them.

I have been searching a lot plus I made some tests and I'm pretty sure you cannot control the visibility of a contentpresenter. Plus - if the ViewModel that is going to be presented by the ContentPresenter is null when view is being showed - it does not even read the property using by boolToVisibilityConverter.

I made a simple workaround - I put ContentPresenter inside a Grid (you can use other type of container obviously) and bound Visibility of the Grid to the boolean properties. It works perfectly.

You should use the AncestorType. The DataContext isn't the same, when you use the ContentPresenter, but you can navigate up in the Visual Tree to find it. In Your case:

Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type Grid}}, Path=ShowStandardWorkspace}"

Where Grid is the first ancestor by default, and its DataContext is used. If you need a second, third etc. ancestor, use the AncestorLevel property with an int value. The converter is fine, I think.

possible sources of error:

  • spelling error ShowStandardWorkspace
  • OnPropertyChanged("ShowStandardWorkspace") not raised in property setter
  • ShowStandardWorkspace property simply not set to false
  • maybe wrong DataContext for the 2nd ContentPresenter
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!