2014-07-18 5 views
1

자신의 항목에서 다른 색상을 사용해야하는 목록 상자에 문제가 있습니다.다른 색상의 WPF 목록 상자

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

지금 내가 문자열 예를 들어 서로 다른 색으로 기록 된 목록 상자에 항목을 추가 할 :

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

내가 원하는 "안녕"(파란색) "내"(적색 그) "이름"(녹색)이 목록 상자에 추가되고 표시됩니다. 이것을 실현할 수있는 방법이 있습니까 ???

+1

두 가지 방법으로 동일한 결과를 얻을 수 있습니다. 그 전에 색칠 규칙을 정의해야 할 수도 있습니다. 당신이 그들을 정의 할 수 있다면 우리는 당신에게 길을 보여 주려고 시도 할 것입니다. – pushpraj

+0

첫 단어 파란색, 두 번째 단어 빨간색, 세 번째 단어 녹색 또는 설명하는 특정 단어 만 원하십니까? – Staeff

+0

'ItemsSource'를 사용하면'Items.Add'와 다른 수정 용도를 사용하지 못하게됩니다. –

답변

1

일부를 강조하기 위해 문자열의 모든 부분에 대해 서로 다른 TextBlock이있을 수있는 곳이 ListBox DataTemplate을 사용하고있는 acheive하는 가능성있는 방법 단어, 일반적으로 우리는 RichTextBox 제어 생각할 수 있습니다. 그러나 그것은 가벼운 무게 조절이 아닙니다. WPF가 풍부한 텍스트를 표시 할 수있게 해주는 많은 컨트롤 (특히 Document 관련)을 지원한다는 것은 행운입니다. 간단한 솔루션 인 경우 각각 ListViewItem에 대한 내용을 나타내는 TextBlock을 사용해야하지만 각 TextBlock 안에 Run 요소를 사용하여 단어를 강조 표시 할 수 있습니다. 먼저 DataTemplate을 사용하여 ListViewItem에 대해 ItemTemplate을 설정해야합니다. 을 사용하여 (각 항목의) ​​문자열 내용을 DataTemplate 안에있는 TextBlock에 바인딩해야합니다. Binding을 사용하면 Converter에 맞춤 코드를 삽입 할 수 있습니다.

코드 뒤에 : 다음은 자세한 코드 나 기본 네임 스페이스 WpfApplication 사용이 데모 여기 네임 스페이스에 대한

<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> 

참고 :

//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 코드에서 편집해야합니다. 또한 XAML 코드에서 항목을 올바르게 추가하면 ItemTemplate이 무시됩니다. Items.Add 또는 데이터 바인딩 (ItemsSource)을 통해 코드를 사용해야합니다.

enter image description here

+1

감사합니다. 그것이 내가 검색 한 것입니다. – lacura

2

당신이 배열로 문자열을 보내드립니다 후 DataTemplate 안에 당신이

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