Silverlight 如何将两个不同的属性绑定到文本块文本和前景?
我已经为多个listboxitems和其中的一些文本块创建了一个模板。在设置中,用户可以将应用程序的背景更改为黑色或白色(然后textblock前景颜色应相应更改为相反的颜色)。如何将文本块文本绑定到一个属性(itemlist(observablecollection)的),并将前景绑定到另一个属性(使用颜色转换器),该属性不在同一数据上下文中(但在设置数据上下文中) 我想做的是:Silverlight 如何将两个不同的属性绑定到文本块文本和前景?,silverlight,xaml,data-binding,windows-phone,Silverlight,Xaml,Data Binding,Windows Phone,我已经为多个listboxitems和其中的一些文本块创建了一个模板。在设置中,用户可以将应用程序的背景更改为黑色或白色(然后textblock前景颜色应相应更改为相反的颜色)。如何将文本块文本绑定到一个属性(itemlist(observablecollection)的),并将前景绑定到另一个属性(使用颜色转换器),该属性不在同一数据上下文中(但在设置数据上下文中) 我想做的是: <DataTemplate x:Key="ArticleItemTemplateClassic">
<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>
谢谢大家! 如果您被迫这样做,您可以为每个项目显式指定不同的
DataContext
。虽然我不确定为什么要将两个与相同的DataTemplate
外观对齐的属性放在不同的容器中。为此,需要为前台属性指定绑定的源。这可以通过多种方式完成,但一个例子是将设置类作为资源公开
例如:
<Grid x:Name="LayoutRoot">
<Grid.Resources>
<!-- If you want to use SettingsFile as a static, you might want to expose an accessor/wrapper class for it here instead. -->
<settings:SettingsFile x:Name="SettingsFileResource" />
</Grid.Resources>
<ListBox ItemsSource="{Binding MyItems}">
<ListBox.ItemTemplate>
<DataTemplate x:Key="ArticleItemTemplateClassic">
<Grid>
<!-- ... -->
<TextBlock Text="{Binding Description}"
<!-- Now change your Binding Path to the target property, and set the source to the resource defined above. -->
Foreground="{Binding BlackBackgroundEnabled, Source={StaticResource SettingsFileResource}, Converter={StaticResource InverseBackgroundColorConverter}}"/>
<StackPanel />
<!-- ... -->
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
然后你会这样使用它:
<TextBlock settings:SettingsFile.BlackBackgroundEnabled="True" />
<TextBlock settings:SettingsFile.BlackBackgroundEnabled="True" />