2015-04-26 28 views
1

我有以下xaml數據模板結合背景屬性

<UserControl 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:Octokit="clr-namespace:Octokit;assembly=Octokit" x:Class="IssuesManagment.UI.POC.Controls.GithubIssue" 
     mc:Ignorable="d" 
     d:DesignHeight="147" d:DesignWidth="295" BorderBrush="#FFD84B4B" BorderThickness="1" Width="Auto" Height="Auto" Margin="0,0,0,2"> 
<UserControl.DataContext> 
    <Octokit:Issue/> 
</UserControl.DataContext> 
<StackPanel> 
    <TextBlock> 
     <Hyperlink NavigateUri="{Binding HtmlUrl}" RequestNavigate="Hyperlink_RequestNavigate"> 
      <TextBlock x:Name="issueTitle" TextWrapping="Wrap" Text="{Binding Title}" FontWeight="Bold" FontSize="16" /> 
     </Hyperlink> 
    </TextBlock> 
    <TextBlock x:Name="issueBody" TextWrapping="Wrap" Text="{Binding Body}" Margin="2"/> 
    <ListBox ItemsSource="{Binding Labels}"> 
     <ListBox.ItemTemplate> 
      <DataTemplate DataType="Octokit:Label"> 
       <TextBlock Text="{Binding Name}"> 
        <TextBlock.Background> 
         <SolidColorBrush Color="{Binding Color}"></SolidColorBrush> 
        </TextBlock.Background> 
       </TextBlock> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
</StackPanel> 
</UserControl> 

我的問題是,在ListBox的項目沒有得到正確的背景顏色

下面是截圖: screen shot of program running to explain issue

特徵標籤例如顏色爲e11d21 該模型被定義爲here

結構的相關部分是:

Issue 
| 
|- Labels : IReadOnlyList<Label> 
          | 
          |- Name 
          |- Color 

任一屬性正確綁定到TextBlock的文本,而不是任何的它的其他性能。

+0

你試過代理技巧,在這裏描述:http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/? – nightcoder

回答

2

你在課堂上有顏色的typeof字符串不變色,所以你需要以下轉換器:

public class StringColorConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var color = (Color)typeof(Colors).GetProperty((String)value).GetValue(null, null); 

     return color; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return String.Empty; 
    } 
} 

而在XAML,資源和例子

<Window.Resources> 
    <local:StringColorConverter x:Key="StringColorConverter"/> 
</Window.Resources> 

<TextBlock Width="200" Height="200"> 
     <TextBlock.Background> 
      <SolidColorBrush Color="{Binding Color, Converter={StaticResource StringColorConverter}}"/> 
     </TextBlock.Background> 
    </TextBlock> 
+0

謝謝。我不得不調整這些代碼,因爲染色沒有領先的'#'。另外 - 沒有內置轉換器從字符串到顏色? –