简体   繁体   English

WPF列表框具有不同的颜色

[英]WPF listbox with different colors

i have a problem with an listbox that should countain different colors in his Items. 我有一个列表框有问题,该列表框应在他的项目中使用不同的颜色。

    <ListBox i:Name="listBox1" ItemsSource="{Binding MyItems_listbox1}" 
     IsSynchronizedWithCurrentItem="True">

Now i want to add an item to the list box were the string is written in different colors for example: 现在,我想向列表框中添加一个项目,以不同​​的颜色写出字符串,例如:

listBox1.Items.Add("hallo my name");

I want that "hallo"(blue) "my"(red) "name"(green) will be added to the listbox and displayed. 我希望将“ hallo”(蓝色)“ my”(红色)“ name”(绿色)添加到列表框中并显示。 Is there some possible way to realize this ??? 有一些可能的方法来实现这一目标吗?

The Probable way to acheive this might be using the ListBox DataTemplate where you will send the string as an array and then inside the DataTemplate you can have different TextBlock for all the parts of string 实现此目的的可能方法可能是使用ListBox DataTemplate ,将字符串作为数组发送,然后在DataTemplate内部,对于字符串的所有部分可以使用不同的TextBlock

<TextBlock Text="hallo " Foreground="Blue" />
<TextBlock Text="my" Foreground="Red" />
<TextBlock Text=" name" Foreground="Green" />

To highlight some word, normally we can thought of RichTextBox control. 为了突出显示一些单词,通常我们可以想到RichTextBox控件。 However it's not a light weight control. 但是,这不是轻量级的控件。 It's fortunate that WPF supports many controls (especially related to Document ) allowing us to display rich text. 幸运的是,WPF支持许多控件(尤其是与Document相关的控件),使我们能够显示富文本格式。 For a lightweight solution, you should just use a TextBlock representing the content for each ListViewItem but we can use the Run elements inside each TextBlock to highlight the words. 对于轻量级解决方案,您应该只使用一个TextBlock表示每个ListViewItem的内容,但是我们可以在每个TextBlock使用Run元素来突出显示单词。 Firstly we need to use DataTemplate to set ItemTemplate for each ListViewItem . 首先,我们需要使用DataTemplate为每个ListViewItem设置ItemTemplate We have to use Binding to bind the string content (of each item) to a TextBlock inside the DataTemplate . 我们必须使用Binding将(每个项目的)字符串内容BindingDataTemplate内部的TextBlock Using Binding allows us to inject some custom code in the Converter . 使用Binding使我们可以在Converter注入一些自定义代码。 Here is the details code: 这是详细代码:

Code behind : 后面的代码

//The main window class
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        //Init the Keywords first
        Keywords.Add("hallo", Brushes.Blue);
        Keywords.Add("my", Brushes.Red);
        Keywords.Add("name", Brushes.Green);

        //Add some items to the ListView
        lv.Items.Add("hallo my name");
        lv.Items.Add("hello my name");
        lv.Items.Add("goodbye your name");            
    }
    //This dictionary used to hold your keywords corresponding to their Brush
    public static Dictionary<string, Brush> Keywords = new Dictionary<string,Brush>();
}

//The converter class
public class InlinesConverter : IValueConverter
{
    object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var content = Convert.ToString(value);
        var dict = MainWindow.Keywords;
        var outString = "<TextBlock xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"  xml:space=\"preserve\">";
        foreach(var word in content.Split(' ')){
            var converted = word;
            Brush fg;
            if (dict.TryGetValue(word, out fg)) {
                var run = new Run(word);
                run.Foreground = fg;
                converted = System.Windows.Markup.XamlWriter.Save(run);
            }
            outString += converted + " ";
        }
        outString += "</TextBlock>";            
        return System.Windows.Markup.XamlReader.Parse(outString);            
    }

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML : XAML

<Window x:Class="WpfApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="SO3" Height="300" Width="300"
    xmlns:local="clr-namespace:WpfApplication"
    >
  <Window.Resources>
    <local:InlinesConverter x:Key="inlinesConverter"/>
  </Window.Resources>
  <Grid>
    <ListView Name="lv">            
        <ListView.ItemTemplate>
            <DataTemplate>                    
                <ContentControl FontSize="20">
                   <Binding Converter="{StaticResource inlinesConverter}"/>
                </ContentControl>
            </DataTemplate>
        </ListView.ItemTemplate>            
    </ListView>
  </Grid>
</Window>

Note about the namespace here, in this demo I used the default namespace WpfApplication . 请注意此处的名称空间,在本演示中,我使用了默认的名称空间WpfApplication If yours is different, you should edit it inside the XAML code. 如果您的密码不同,则应在XAML代码中对其进行编辑。 Also note that the ItemTemplate is ignored if you add the items right in the XAML code. 还要注意,如果您直接在XAML代码中添加项目,则将忽略ItemTemplate We have to use the code behind either via Items.Add or data binding (with ItemsSource ). 我们必须通过Items.Add或数据绑定(使用ItemsSource )使用背后的代码。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM