Reputation: 25408
Long ago, I looked at this MSDN walkthrough. It implements a color editor, and the tooltip uses the color's name like "Red" or "Blue".
Today, I'm implementing a ListBox that is similar; it displays a box with the color and the name of the color next to it. Except in my application, all of the color names display as the hex values like #FFFF0000 and #FF0000FF. Why?
Here's the ColorsList
class used in both projects:
public ColorsList()
{
Type type = typeof(Colors);
foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.Static))
{
if (propertyInfo.PropertyType == typeof(Color))
{
Add((Color)propertyInfo.GetValue(null, null));
}
}
}
This XAML snippet makes the tooltip use the color name in the MSDN project (you can see the rest of the code in the walkthrough):
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Tag="{Binding}" Command="{x:Static PropertyEditing:PropertyValueEditorCommands.ShowInlineEditor}">
<Button.Template>
<ControlTemplate>
<Border Width="30" Height="30" BorderBrush="Black" BorderThickness="1" CornerRadius="5">
<Rectangle Width="22" Height="22" ToolTip="{Binding}">
<Rectangle.Fill>
<SolidColorBrush Color="{Binding}"/>
</Rectangle.Fill>
</Rectangle>
</Border>
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
Here's my XAML that produces the hex codes:
<ListBox x:Name="lstColors" Grid.Row="1" ItemsSource="{StaticResource colors}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle Stroke="Black"
StrokeThickness="3"
Width="24"
Height="24"
RadiusX="5"
RadiusY="5">
<Rectangle.Fill>
<SolidColorBrush Color="{Binding}" />
</Rectangle.Fill>
</Rectangle>
<TextBlock Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
It looks the same to me; what's the difference?
Upvotes: 0
Views: 414
Reputation: 25408
It turns out design-time is different from run-time. The MSDN example is used as an extended property editor. I took a friend's advice and tried exposing it as a runtime control, and magically it's getting hash names for colors instead of friendly names. Neat.
Upvotes: 0
Reputation: 1024
Not exactly an answer to your question, more of an observation:
If you change ColorsList to inherit from ObservableCollection<string>
instead of ObservableCollection<Color>
and modify the following line:
Add((Color)propertyInfo.GetValue(null, null));
to
Add(propertyInfo.Name);
your code will work as you want it to work. Instead of converting Color to color name, this is going the other way around - using the built-in conversion from color name to Color.
As a side note, I tried the XAML code from the MSDN sample (only the part you're citing) but the tooltips display color codes and not color names.
Upvotes: 1