为所选文本或插入符号后面键入的任何内容设置颜色 [英] Colour selected text or anything typed after the caret
问题描述
大家好,
我正在尝试让这个小应用程序为按下按钮时选择的文本着色,或者如果未选择任何内容,则在键入时对插入符号后的所有内容进行着色.
这可行,但是我有一个错误,如果我在两个字符之间插入插入符号并按一个按钮,则一切都是彩色的.我不希望这样,只是插入符号之后出现的所有内容.
我的假设是``rtb.Selection.ApplyPropertyValue(TextElement.ForegroundProperty,colour);''假设其两侧的所有内容均已被``选择''.
有人可以帮忙吗?
提前谢谢您.
Hi guys,
I''m trying to get this little app to colour text that is selected when a button is pressed, or colour anything that comes after the caret when typing if nothing is selected.
This works, but I have a bug where, if I insert the caret between two characters and press a button, EVERYTHING is coloured. I do not want this, just everything that comes after the caret.
My assumption is that ''rtb.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, colour);'' is assuming everything on either side of it is ''selected''.
Can anyone assist, perhaps?
Thank you in advance.
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="400">
<Grid removed="Gray">
<RichTextBox removed="Black" Foreground="White" Height="150" HorizontalAlignment="Right" Name="rtb" VerticalAlignment="Top" Width="354" Margin="0,12,12,0" />
<Button Background="Blue" Content="Blue" Height="75" HorizontalAlignment="Left" Margin="139,174,0,0" Name="button2" VerticalAlignment="Top" Width="100" Click="btnColour_Click" Foreground="Yellow" />
<Button Background="Red" Content="Red" Height="75" HorizontalAlignment="Left" Margin="12,174,0,0" Name="button1" VerticalAlignment="Top" Width="100" Click="btnColour_Click" Foreground="Blue" />
<Button Background="Yellow" Content="Green" Height="75" HorizontalAlignment="Left" Margin="266,174,0,0" Name="button3" VerticalAlignment="Top" Width="100" Click="btnColour_Click" Foreground="Red" />
</Grid>
</Window>
private void colourText(Brush colour)
{
TextPointer startPointer = rtb.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward);
TextPointer endPointer = rtb.Document.ContentEnd.GetNextInsertionPosition(LogicalDirection.Backward);
TextRange range = new TextRange(startPointer, endPointer);
int length = range.Text.Length;
rtb.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, colour);
if (length == 0)
{
rtb.Foreground = colour;
}
}
private void btnColour_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
Brush colour = btn.Background;
colourText(colour);
rtb.Focus();
}
推荐答案
看来,解决此问题的唯一方法是使用OnTexTInput事件,并在键入时手动更改每个字母.我担心速度问题,但到目前为止看来仍然可行.
(也许有一天我会习惯这种解决方案的事情!)
It looks like the only way to resolve this I could come up with was to use the OnTexTInput event and have it manually change every letter when typed. I fear for the issues of speed, but so far it seems to work.
(I''ll get used to this solution thing one day, maybe!)
这篇关于为所选文本或插入符号后面键入的任何内容设置颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!