绑定到背景属性的数据模板

时间:2015-04-26 23:08:26

标签: wpf xaml data-binding

我有以下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的Text,但不能绑定到任何其他属性。

1 个答案:

答案 0 :(得分:2)

类中的颜色是字符串而不是颜色,因此您需要以下转换器:

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>
相关问题