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;
Edit : The main problem was binding TextBox. I simply fixed problem by changing TextBox code to this :
<TextBox Foreground="{Binding ElementName=CBox, Path=SelectedItem.Name}"/>
but Clemens' approach is better so I proceed to use it.
1条答案
按热度按时间oxiaedzo1#
我建议将一个匿名对象集合分配给组合框的ItemsSource,该集合包含
Name
和Brush
属性。下面的代码使用Brushes
类的所有公共静态Brush
属性,而不是Colors
类的Color
属性。下面的表达式首先获取
System.Windows.Media.Brushes
类的所有公共静态属性,类似于已经对Colors
类所做的操作。然后,它将PropertyInfo
对象的集合Map到一个匿名类的示例集合,该匿名类具有Name
和Brush
属性。通过调用每个PropertyInfo的GetValue
方法创建Brush。然后绑定这些数据,如下所示:TextBox的
Foreground
属性绑定到选定项(即匿名类的选定示例)的Brush
属性。