像这样的东西应该可以解决问题
public MainWindow()
{
InitializeComponent();
textBlock1.Inlines.Add(new Run("One "));
textBlock1.Inlines.Add(new Run("Two "));
textBlock1.Inlines.Add(new Run("Three "));
}
private SolidColorBrush _blackBrush = new SolidColorBrush(Colors.Black);
private SolidColorBrush _redBrush = new SolidColorBrush(Colors.Red);
private Run _selectedRun;
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
var run = e.OriginalSource as Run;
if (run != null)
{
if (_selectedRun != null)
{
_selectedRun.Foreground = _blackBrush;
if (_selectedRun == run)
{
return;
}
}
run.Foreground = _redBrush;
_selectedRun = run;
}
}
但是您必须使用“MouseDown”或“MouseUp”处理单击,因为 Textblock 没有 Click 事件
要在某个索引处着色,这是一个简单的示例。
private void ColorInlineAtIndex(InlineCollection inlines, int index, Brush brush)
{
if (index <= inlines.Count - 1)
{
inlines.ElementAt(index).Foreground = brush;
}
}
用法:
ColorInlineAtIndex(textBlock1.Inlines, 2, new SolidColorBrush(Colors.Blue));
查找位置:
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
var run = e.OriginalSource as Run;
if (run != null)
{
int position = (sender as TextBlock).Inlines.ToList().IndexOf(run);
}
}