WPF绑定Window上下文FontColor功能正常却报属性不存在错误
错误原因
WPF绑定引擎解析Foreground="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext.FontColor}"时,会先尝试在当前数据上下文(即DeviceOverview实例)中查找路径前缀DataContext,但DeviceOverview类未定义DataContext属性,因此抛出找不到FontColor的错误提示(本质是找不到DataContext属性引发的连锁提示)。尽管实际运行时绑定能正确定位到Window的DataContext,但绑定引擎的初始路径验证逻辑会触发该错误。
解决方法
以下几种方式均可修复问题,消除错误提示且不影响绑定功能:
方式一:给路径添加括号,明确整体指向
修改Label的Foreground绑定,用括号包裹路径,让绑定引擎明确整个路径基于找到的Window元素:
Foreground="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=(DataContext.FontColor)}"
方式二:使用ElementName绑定(需给Window命名)
先给Window设置x:Name属性,例如x:Name="MainWindow",再修改绑定:
Foreground="{Binding ElementName=MainWindow, Path=DataContext.FontColor}"
方式三:通过ItemsControl的DataContext间接绑定
ItemsControl的DataContext与Window一致(均为Window的ViewModel),可通过RelativeSource找到ItemsControl,再绑定其DataContext的FontColor:
Foreground="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl}, Path=DataContext.FontColor}"
内容的提问来源于stack exchange,提问作者Riccardo Palma
相关产品推荐
相关产品推荐

