My scenario is as follows, and I hope someone finds it useful:
I have a ComboBox control in a wpf window in which I want to display all the colors from the Brushes class.
MainWindow.xaml
In the window declaration, I added the following link:
xmlns:converters="clr-namespace:MyProjectName.Converters"
In the Window.Resources section, I registered a converter named "ColorConverter":
<converters:StringToColorConverter x:Key="ColorConverter"/>
And somewhere in my xaml code I implemented the following combo box:
<ComboBox Grid.Column="1" Grid.Row="3" ItemsSource="{Binding VBColors}" Margin="5,5,0,5" HorizontalContentAlignment="Stretch"> <ComboBox.ItemTemplate> <DataTemplate> <Rectangle Height="20" Fill="{Binding Path=., Converter={StaticResource ColorConverter}}"/> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox>
MainWindow.cs
private List<string> _vbColors = typeof(Brushes).GetProperties().Select(x => x.Name).ToList(); public List<string> VBColors { get { return _vbColors; } }
StringToColorsConverter.cs
[ValueConversion(typeof(bool), typeof(SolidColorBrush))] public sealed class StringToColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var stringValue = (string)value; SolidColorBrush solidColor = (SolidColorBrush)new BrushConverter().ConvertFromString(stringValue); return solidColor; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }
Some tips ....
In the ComboBox.ItemTemplate binding you will find the binding to "Binding Path =". => Since the color list is not a list of objects, but a list of strings, Binding Path =. this is a way to bind a control to a string name
Also ... Set te ComboBox HorizontalContentAlignment = "Stretch" to stretch the rectangle to the width of the ComboBox ... try to see the difference.
Keep coding, jj