XAML 在文本框中键入文字时,如何使用组合框中的颜色来更改文字的颜色?

mctunoxg  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(184)

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.

oxiaedzo

oxiaedzo1#

我建议将一个匿名对象集合分配给组合框的ItemsSource,该集合包含NameBrush属性。下面的代码使用Brushes类的所有公共静态Brush属性,而不是Colors类的Color属性。
下面的表达式首先获取System.Windows.Media.Brushes类的所有公共静态属性,类似于已经对Colors类所做的操作。然后,它将PropertyInfo对象的集合Map到一个匿名类的示例集合,该匿名类具有NameBrush属性。通过调用每个PropertyInfo的GetValue方法创建Brush。

CBox.ItemsSource = typeof(Brushes)
    .GetProperties(BindingFlags.Static | BindingFlags.Public)
    .Select(p => new { Name = p.Name, Brush = p.GetValue(null) });

然后绑定这些数据,如下所示:TextBox的Foreground属性绑定到选定项(即匿名类的选定示例)的Brush属性。

<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}"/>

相关问题