
Introduction
This simple application lists brushes in System.Windows.Media.Brushes
in a ListBox
by using Reflection and the WPF Data Binding features.
Using the code
First, add a ListBox
and set a DataTemplate
in the ItemTemplate
attribute:
<ListBox Name="lsbBrushes" ItemsSource="{Binding}" Margin="10"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy Name" Click="CopyName_Click"></MenuItem>
<MenuItem Header="Copy Hex" Click="CopyHex_Click"></MenuItem>
</ContextMenu>
</ListBox.ContextMenu>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="130"/>
</Grid.ColumnDefinitions>
<Rectangle Fill="{Binding Path=Name}"
Stroke="Black" Margin="5"
StrokeThickness="1" Height="50" Width="100"/>
<StackPanel Grid.Column="1">
<Label Content="{Binding Path=Name}" />
<Label Content="{Binding Path=Hex}" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And now, write the binding class and item class like this:
class WPFBrushList : List<WPFBrush>
{
public WPFBrushList()
{
Type BrushesType = typeof(Brushes);
PropertyInfo[] brushesProperty = BrushesType.GetProperties();
foreach (PropertyInfo property in brushesProperty)
{
BrushConverter brushConverter = new BrushConverter();
Brush brush = (Brush)brushConverter.ConvertFromString(property.Name);
Add(new WPFBrush(property.Name, brush.ToString()));
}
}
}
class WPFBrush
{
public WPFBrush(string name, string hex)
{
Name = name;
Hex = hex;
}
public string Name { get; set; }
public string Hex { get; set; }
}
At last, set the binding class to ListBox.DataContext
:
public partial class Window1 : Window
{
private WPFBrushList _brushes = new WPFBrushList();
public Window1()
{
InitializeComponent();
lsbBrushes.DataContext = _brushes;
}
private void CopyName_Click(object sender, RoutedEventArgs e)
{
if (lsbBrushes.SelectedIndex != -1)
Clipboard.SetText(((WPFBrush)lsbBrushes.SelectedItem).Name);
}
private void CopyHex_Click(object sender, RoutedEventArgs e)
{
if (lsbBrushes.SelectedIndex != -1)
Clipboard.SetText(((WPFBrush)lsbBrushes.SelectedItem).Hex);
}
}
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.