일부를 강조하기 위해 문자열의 모든 부분에 대해 서로 다른 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
)을 통해 코드를 사용해야합니다.
두 가지 방법으로 동일한 결과를 얻을 수 있습니다. 그 전에 색칠 규칙을 정의해야 할 수도 있습니다. 당신이 그들을 정의 할 수 있다면 우리는 당신에게 길을 보여 주려고 시도 할 것입니다. – pushpraj
첫 단어 파란색, 두 번째 단어 빨간색, 세 번째 단어 녹색 또는 설명하는 특정 단어 만 원하십니까? – Staeff
'ItemsSource'를 사용하면'Items.Add'와 다른 수정 용도를 사용하지 못하게됩니다. –