我有以下数据模板:
<Page.Resources>
<local:ColorToBrushConverter x:Key="ColorToBrush"/>
<DataTemplate x:Key="PokedexListTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" Grid.Column="0"/>
<StackPanel Grid.Column="1">
<TextBlock Text="Type1" Foreground="{Binding Type1.Color, Converter={StaticResource ColorToBrush}}"/>
<TextBlock Text="Type2" Foreground="{Binding Type2.Color, Converter={StaticResource ColorToBrush}}"/>
</StackPanel>
</Grid>
</DataTemplate>
</Page.Resources>
这里填充了Pokemon
个对象:
public class Pokemon()
{
public PokeType Type1 { get; }
public PokeType Type2 { get; }
public string Name { get; }
}
反过来包含PokeType
个对象:
public class PokeType()
{
public string TypeColor { get; } // "#FF0000", can be changed if that'd make things easier
public string Name { get; }
}
转换器
public class ColorToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string culture)
{
return new SolidColorBrush(Colors.Red);
}
public object ConvertBack(object value, Type targetType, object parameter, string culture)
{
throw new NotSupportedException();
}
private static Color Parse(string color)
{
var offset = color.StartsWith("#") ? 1 : 0;
var a = Byte.Parse(color.Substring(0 + offset, 2), NumberStyles.HexNumber);
var r = Byte.Parse(color.Substring(2 + offset, 2), NumberStyles.HexNumber);
var g = Byte.Parse(color.Substring(4 + offset, 2), NumberStyles.HexNumber);
var b = Byte.Parse(color.Substring(6 + offset, 2), NumberStyles.HexNumber);
return Color.FromArgb(a, r, g, b);
}
}
如何以最佳方式达到所需的效果(将类型名称绑定为文本并将其与类型的颜色着色)?谢谢!
答案 0 :(得分:0)
我建议使用IValueConverter
- 让Foreground
绑定为Type1.TypeColor和Type2.TypeColor,但添加Converter
参数。
你还需要创建一个String to Color转换器(你可以在这里找到一个例子:http://compiledexperience.com/blog/posts/useful-calue-converters/)
用法如下:
<Page.Resources>
<ColorToBrushConverter x:Key="ColorToBrush"/>
</Page.Resources>
...
<TextBlock Text="{Binding Type1.Name}" Foreground="{Binding Type1.Color, Converter={StaticResource ColourToBrushConverter}}"/>