我已经为多个listboxitems和一些文本块创建了一个模板 . 在设置中,用户可以将应用程序的背景更改为黑色或白色(然后文本块前景色应相应地更改相反) . 我如何 bind 文本块 text to one property (项目列表(observablecollection))和 foreground to another property (带颜色的转换器)不在同一个datacontext中(但在settings-datacontext中)?
我想做什么:
<DataTemplate x:Key="ArticleItemTemplateClassic">
<Grid>
<!-- ... --->
<TextBlock Text="{Binding Description}"
Foreground="{Binding SettingsFile.BlackBackgroundEnabled,
Converter={StaticResource InverseBackgroundColorConverter}}"/>
<!-- The Context of the Foreground (SettingsFile.BlackBackgroundEnabled) -->
<!-- should be not the same as where I bind Description -->
</StackPanel>
<!-- ... --->
</Grid>
</DataTemplate>
谢谢!
2 回答
为此,您需要指定Foreground属性的绑定源 . 这可以通过多种方式完成,但一个示例是将Settings类公开为资源 .
例如:
替代方案,使用AttachedProperty可能更清洁 . 例如:
然后你会像这样使用它:
如果您被迫这样做,您可以为每个项目明确指定不同的
DataContext
. 虽然我不确定为什么你有两个属性与同一个DataTemplate
的外观一致,位于不同的容器中 .