2013-06-30 31 views
1
<ListBox> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <Textblock Text={Binding Path=Content} Foreground={Binding Path=TextColor}/> 
      </DataTemplate> 
     <ListBox.ItemTemplate> 
    </ListBox> 

嗨,我正在開發WP8中的書籍閱讀器應用程序。我有一個列表,我使用列表框來顯示段落。您可以在我的代碼中看到每個段落內容綁定到一個文本塊。在Paragraph類中,我定義了一個字段調用TextColor來將文本塊的前景顏色綁定到它。現在,每次用戶更改顏色時,我都必須遍歷故事中的所有段落並更改TextColor的值。有沒有什麼辦法將ListboxItem的兩個不同的屬性(即前景和文本)分別綁定到不同的源>所以我只需要改變前景一次。感謝將XAML中的一個ElementUI綁定爲2個源

回答

0

KooKiz解決方案非常好。但是,如果您不想包含任何屬性來管理前景色或任何視覺屬性,那麼您可以簡單地將其設置爲靜態資源並將其綁定到該位置,而不必在模型中修改它們。

例如,您可以定義ForegroundResouces類,並添加您的應用程序需要的不同類型的前景。

在App.xaml中

<Application.Resources> 
    <local:ForegroundResouces xmlns:local="clr-namespace:YOUR-NAMESPACE" x:Key="ForegroundResouces" /> 
</Application.Resources> 

然後定義你的類

public class ForegroundResouces { 
    public static Brush TitleForeground { get; set; } 
    public static Brush ContentForeground { get; set; } 
    // ... 
} 

然後定義你的綁定

<ListBox> 
    <ListBox.ItemTemplate> 
    <DataTemplate> 
     <Textblock 
     Text={Binding Path=Content} 
     Foreground={Binding Path=ContentForeground, Source={StaticResource ForegroundResouces} /> 
    </DataTemplate> 
    <ListBox.ItemTemplate> 
</ListBox> 

然後,你可以簡單地通過修改靜態屬性

改變前景
ForegroundResources.ContentForeground = new SolidBrush(Colors.Red); 

您可以對不同的主題進行排序,但如果您有多個可視化屬性需要管理,則此解決方案可能只值得。

+1

如果我沒有錯,您的解決方案將不允許在頁面加載後更改顏色(因爲沒有通知機制)。如果這是一個問題,那麼'ForegroundResources'類應該實現'INotifyPropertyChanged',並且屬性不應該是靜態的。 –

+0

@KooKiz是的,這是正確的。 –

0

有方法可以爲您的綁定指定不同的來源。例如,你可以使用ElementName在你的列表框指向並檢索其的DataContext:

<ListBox x:Name="MyList" ItemsSource="{Binding Path=Paragraphs}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Textblock Text="{Binding Path=Content}" Foreground="{Binding Path=DataContext.TextColor, ElementName=MyList}"/> 
     </DataTemplate> 
    <ListBox.ItemTemplate> 
</ListBox> 

但在你的情況下,它只是設置父名單上的Foreground性質可能更容易。它將自動適用於所有子控件:

<ListBox x:Name="MyList" ItemsSource="{Binding Path=Paragraphs}" Foreground="{Binding Path=TextColor}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Textblock Text="{Binding Path=Content}" /> 
     </DataTemplate> 
    <ListBox.ItemTemplate> 
</ListBox> 
相關問題