簡體   English   中英

更改文本塊中單擊的文本的格式

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

我有一個textBlock,向其中添加了一些文本,例如:

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

如何添加單擊事件以更改已單擊的內聯文本的顏色?

例如,如果單擊“一個”,我希望它具有紅色字體; 然后如果單擊“兩個”,我希望“一個”再次為黑色,而“兩個”為紅色,以便最后單擊的單詞的顏色為紅色。

我對使用c#和wpf進行編程非常陌生。

謝謝你的幫助

這樣的事情應該可以解決問題

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM