2013-03-02 44 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的外觀對齊,並位於不同的容器中。

相關問題