简体   繁体   English

更改文本块中单击的文本的格式

[英]Changing the formatting of clicked text in a textblock

I have a textBlock to which I've added some text eg as follows: 我有一个textBlock,向其中添加了一些文本,例如:

textBlock1.Inlines.Add(new Run("One "));
textBlock1.Inlines.Add(new Run("Two "));
textBlock1.Inlines.Add(new Run("Three "));

How can I add a click event that changes the color of the text of the inline that has been clicked? 如何添加单击事件以更改已单击的内联文本的颜色?

eg if "One" is clicked I'd like it to have a red font; 例如,如果单击“一个”,我希望它具有红色字体; then if "Two" is clicked, I'd like "One" to be black again, and "Two" to be red, so that the color of the last word clicked is red. 然后如果单击“两个”,我希望“一个”再次为黑色,而“两个”为红色,以便最后单击的单词的颜色为红色。

I'm fairly new to programming with c# and wpf. 我对使用c#和wpf进行编程非常陌生。

Thanks for your help 谢谢你的帮助

Something like this should do the trick 这样的事情应该可以解决问题

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

But you will have to handle click with "MouseDown" or "MouseUp" as Textblock does not have Click event 但是您将不得不使用“ MouseDown”或“ MouseUp”处理单击,因为Textblock没有Click事件

To color one at a certain index this is a quick example. 要为某个索引上色,这是一个简单的示例。

private void ColorInlineAtIndex(InlineCollection inlines, int index, Brush brush)
{
    if (index <= inlines.Count - 1)
    {
          inlines.ElementAt(index).Foreground = brush;
    }
}

Usage: 用法:

 ColorInlineAtIndex(textBlock1.Inlines, 2, new SolidColorBrush(Colors.Blue));

Find position: 查找位置:

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);
    }
}

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

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