像這樣的東西應該做的伎倆
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」的文本塊沒有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);
}
}
什麼TextBlock的? Maibe TextBox? –
據我瞭解,我有更多的控制與textBlock不同風格的文本格式,我不需要文本是可選擇或可編輯的。 –