【发布时间】:2012-09-06 01:52:25
【问题描述】:
所以我有一些类似于以下的代码:(请原谅任何拼写错误——我试图在帖子的 SO 编辑器中简化)
<my:CustomContentControl>
<my:CustomContentControl.Style>
<Style TargetType="{x:Type my:CustomContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=CurrentView}" Value="MyCustomView">
<Setter Property="Content">
<Setter.Value>
<my:CustomView DataContext="{Binding DataContextForMyCustomView"/>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</m:CustomContentControl.Style>
</my:CustomContentControl>
问题是每当DataTrigger 发生时,setter 确实 将Content 属性设置为my:CustomView,但它不 绑定DataContext .如果我将相同的代码移到触发器之外,DataContext 绑定就可以正常工作。
有什么想法吗?如果这是某种限制,是否有任何解决方法?
更新:
我在输出窗口中收到以下错误:
System.Windows.Data Error: 3 : Cannot find element that provides DataContext. BindingExpression:Path=DataContextForMyCustomView; DataItem=null; target element is 'CustomView' (Name='customView'); target property is 'DataContext' (type 'Object')
【问题讨论】:
-
您的输出窗口中是否有关于此绑定的任何错误或警告消息?
-
@Miklós:很好的建议,谢谢。呃,我没想到绑定错误出现在输出窗口中!现在更新我的问题与错误...
-
@HolySamosa 你的
UserControl在什么位置?您发布的错误听起来像是在没有DataContext的对象中,例如DataGridColumn.Header。此外,如果多个对象应用该样式,您真的应该使用ContentTemplate而不是Content以避免异常:) -
@Rachel:用户控件是我创建的 MVVM 视图。此外,我试图清理我的示例代码以省略我的实现细节。我使用的 ContentControl 实际上是来自 MahApps 的处理转换的自定义控件。我正在尝试使用您在回答 Bartek 问题时链接到的文章中的 BindingProxy。我似乎在这方面取得了进展。 (当我试图做一些脑残的事情时,我删除了我之前的评论。:-)
-
@Rachel:是的,Thomas Levesque 的BindingProxy 解决了我的问题。谢谢!如果您想留下带有文章链接的答案,我很乐意为您提供正确答案!
标签: wpf xaml mvvm binding datacontext