[英]ContentControl with DataTemplateSelector and bound Content
I have the following ContentControl
two-way binded with a Current
property that shows the current selection of my ListView
. 我有以下
ContentControl
双向绑定与Current
属性,显示我的ListView
的当前选择。
<ContentControl Content="{Binding Current}" ContentTemplateSelector="{StaticResource myTemplateSelector}">
It uses a DataTemplateSelector
that returns 1 of 2 DataTemplates
, one when the Content
is null
and the other one when it is not. 它使用
DataTemplateSelector
返回2个DataTemplates
中的一个,一个在Content
为null
时,另一个在不DataTemplates
。
When I start my app the Current
property is null
and the correct DataTemplate
is applied. 当我启动我的应用程序时,
Current
属性为null
并且应用了正确的DataTemplate
。
When I select one ListViewItem
, Current
property is not null
and the ContentControl DataTemplate
changes as it should. 当我选择一个
ListViewItem
, Current
属性不为null
, ContentControl DataTemplate
会按原样更改。
When I unselect the ListViewItem
, Current
property is null
again and the ContentControl
disappears and none of the DataTemplates
are applied. 当我取消选择
ListViewItem
, Current
属性再次为null
, ContentControl
消失,并且不应用任何DataTemplates
。
I made breakpoints and output some data to the console and I discover that DataTemplateSelector does not runs when Current
changes to null. 我创建了断点并将一些数据输出到控制台,我发现当
Current
更改为null时 , DataTemplateSelector不会运行。 However it runs the first time when it is also null. 但是它第一次运行时它也是null。 So I don't understand why is this happening.
所以我不明白为什么会这样。 Anyone had this issue or a similar one?
有人遇到过这个问题还是类似问题?
When you deselect the item, selected item of the list box becomes null, thus the binding to Current
cannot find the property. 取消选择该项时,列表框的选定项将变为空,因此绑定到
Current
无法找到该属性。
In this case, trying to access Current
doesn't return null
it returns null reference exception which is swallowed by binding. 在这种情况下,尝试访问
Current
不会返回null
它将返回由引用吞噬的null引用异常。
I'm assuming that you bind to the selected item (whether directly off the list box or routed through view model) in some way. 我假设您以某种方式绑定到所选项目(无论是直接在列表框之外还是通过视图模型进行路由)。 Something like:
就像是:
<Grid DataContext="{Binding SelectedItem}">
<ContentControl ..../>
</Grid>
If so, you'd need to change bindings and the logic of template selector: 如果是这样,您需要更改绑定和模板选择器的逻辑:
At ContentControl: 在ContentControl:
Content="{Binding }"
In related data templates, you'd need to add Current.
在相关数据模板中,您需要添加
Current.
at the beginning of all paths in all bindings. 在所有绑定中的所有路径的开头。
In data template selector instead of checking the value, check the Current
property (and if the casting of value fails, consider it null). 在数据模板选择器中,而不是检查值,检查
Current
属性(如果值的转换失败,则将其视为null)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.