簡體   English   中英

如何使用組合框中的 colors 在文本框中鍵入時更改文本的顏色?

[英]how can I change the color of my text while I type in the text box by using the colors in combo box?

我創建了一個組合框,其中包括 Colors class 中的所有 colors。 我想通過從 ComboBox 中選擇顏色來更改 TextBox 的前景色。 我怎樣才能做到這一點?

你能解釋一下 {Binding Name} 中的邏輯嗎?我不明白為什么我使用 Name 關鍵字,但它起作用了。

<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();       
}

我嘗試了這種方法,它給出了錯誤

tBox.Foreground = (Colors)CBox.SelectedItem;

我建議將一組具有NameBrush屬性的匿名對象分配給 ComboBox 的 ItemsSource。 下面的代碼使用了Brushes class 的所有公共 static Brush屬性,而不是ColorsColor屬性

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

然后像這樣綁定這些數據:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM