2013-03-02 45 views
0

我为多个listboxitems和一些文本块内部创建了一个模板。在设置中,用户可以将应用程序的背景更改为黑色或白色(然后,文本块前景颜色应相应改变)。我怎样才能绑定的的TextBlocks 文本到一个属性(该ITEMLIST的(的ObservableCollection))和前景他人财产(与该颜色的转换器),这是不一样的datacontext(但在设置-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> 

谢谢!

回答

0

为此,您需要指定“前景”属性的“绑定来源”。这可以通过很多方式完成,但一个示例是将Settings类作为资源公开。

例如:

<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> 

Alternativelty,这可能是清洁剂使用AttachedProperty此相反。 EG:

public static bool GetBlackBackgroundEnabled(DependencyObject obj) 
{ 
    return (bool)obj.GetValue(BlackBackgroundEnabledProperty); 
} 

public static void SetBlackBackgroundEnabled(DependencyObject obj, bool value) 
{ 
    obj.SetValue(BlackBackgroundEnabledProperty, value); 
} 

// Using a DependencyProperty as the backing store for BlackBackgroundEnabled. This enables animation, styling, binding, etc... 
public static readonly DependencyProperty BlackBackgroundEnabledProperty = 
    DependencyProperty.RegisterAttached("BlackBackgroundEnabled", typeof(bool), typeof(Control), new PropertyMetadata(false, (s, e) => 
     { 
      Control target = s as Control; 
      SolidColorBrush brush = new SolidColorBrush(); 

      // Logic to determine the color goes here 
      if (GetBlackBackgroundEnabled(target)) 
      { 
       brush.Color = something; 
      } 
      else 
      { 
       brush.Color = somethingElse; 
      } 

      target.Foreground = brush; 
     })); 

然后你会使用这样的:

<TextBlock settings:SettingsFile.BlackBackgroundEnabled="True" /> 
0

如果您被迫这样做,您可以为每个项目明确指定一个不同的DataContext。虽然我不确定为什么你会有两个属性与同一个DataTemplate的外观对齐,并位于不同的容器中。

相关问题