I created a Combo Box which includes all colors in Colors class. I'd like to change TextBox's foreground color by selecting the color from ComboBox. How can I do that?
And can you also explain the logic in {Binding Name}, I did not understand why I used Name keyword but it worked.
<StackPanel>
<ComboBox Name="CBox" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle Width="20" Height="20" Fill="{Binding Name}"/>
<TextBlock Text="{Binding Name}" Margin="5" FontSize="20"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBox x:Name="tBox"/>
</StackPanel>
public MainWindow()
{
InitializeComponent();
CBox.ItemsSource = typeof(Colors).GetProperties();
}
I tried this approach and it gave error
tBox.Foreground = (Colors)CBox.SelectedItem;
CodePudding user response:
I would suggest to assign a collection of anonymous objects with a Name
and a Brush
property to the ItemsSource of the ComboBox. The code below uses all the public static Brush
properties of the Brushes
class, instead of the Color
properties of the Colors
class.
CBox.ItemsSource = typeof(Brushes)
.GetProperties(BindingFlags.Static | BindingFlags.Public)
.Select(p => new { Name = p.Name, Brush = p.GetValue(null) });
Then bind this data like this:
<ComboBox Name="CBox" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle Width="20" Height="20" Fill="{Binding Brush}"/>
<TextBlock Text="{Binding Name}" Margin="5"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBox Foreground="{Binding SelectedItem.Brush, ElementName=CBox}"/>