[英]WPF EditingCommands is not working when RichTextBox is just load/empty?
這是一個非常簡單的代碼示例:
<DockPanel>
<ToolBar DockPanel.Dock="Top" IsTabStop="False">
<ToggleButton MinWidth="40" Command="EditingCommands.ToggleBold" CommandTarget="{Binding ElementName=XAMLRichBox}" TextBlock.FontWeight="Bold" IsTabStop="False">B</ToggleButton>
</ToolBar>
<RichTextBox x:Name="XAMLRichBox" SpellCheck.IsEnabled="True" MinHeight="100"/>
</DockPanel>
當我運行它時,在RichTextBox
鍵入內容后,我可以使用ToggleButton
來獲得BOLD效果,一切都很好。
但是如果我在輸入RichTextBox
之前單擊ToggleButton
(無論RichTextBox
獲得焦點),雖然ToggleButton
變為Checked
,但我的RichTextBox
仍然使用正常樣式(不是BOLD ),直到我再次單擊ToggleButton
。 這是一個錯誤嗎? 我該怎么走? 謝謝!
我找到了一個半解決方案,我想我會分享,因為這個問題在網絡的任何地方都沒有得到解答,我認為很多人都遇到了問題。
我在構造函數中設置了一個Variable NewInput 。 當richTextBox中的第一個輸入被觸發時,我將只應用我需要的每個格式並將其傳遞給控件。
private bool NewInput;
private void richTxt_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (NewInput)
{
richTxt.BeginChange();
TextPointer startPosition = richTxt.Selection.Start;
Run r = new Run(e.Text, startPosition);
if (IsSelectionBold)
{
r.FontWeight = FontWeights.Bold;
}
if (IsSelectionItalic)
{
r.FontStyle = FontStyles.Italic;
}
if (IsSelectionUnderlined)
{
r.TextDecorations = TextDecorations.Underline;
}
r.FontSize = double.Parse(SelectedFontHeight);
r.FontFamily = new FontFamily(SelectedFont);
richTxt.EndChange();
NewInput = false;
e.Handled = true;
richTxt.CaretPosition = richTxt.CaretPosition.GetPositionAtOffset(1);
}
}
然后我在正確的地方更換了carret。 像這樣,即使RichTextBox中沒有任何內容,也會保留格式化。
我相信有一天它會對某人有所幫助。
Mainwindow.xaml
<DockPanel>
<ToolBar
DockPanel.Dock="Top"
IsTabStop="False">
<ToggleButton
x:Name="boldButton"
Command="EditingCommands.ToggleBold"
CommandTarget="{Binding ElementName=XAMLRichBox}"
TextBlock.FontWeight="Bold"
ToolTip="Bold">
B
</ToggleButton>
</ToolBar>
<RichTextBox
x:Name="XAMLRichBox"
SpellCheck.IsEnabled="True"
SelectionChanged="SynchronizeWith"
MinHeight="100" />
</DockPanel>
Mainwindow.xaml.cs
private void SynchronizeWith(object sender, RoutedEventArgs e)
{
object currentValue = XAMLRichBox.Selection.GetPropertyValue(TextElement.FontWeightProperty);
boldButton.IsChecked = (currentValue == DependencyProperty.UnsetValue) ? false : currentValue != null && currentValue.Equals(FontWeights.Bold);
}
@Sinity很接近,但是當插入符號放在文本塊中時,該解決方案不起作用,只有當它位於最后時。
Run的末尾有兩個位置: Run.ContentEnd
和Run.ElementEnd
。 似乎ContentEnd
“正好在運行之外”(因此輸入的任何新文本都不會采用運行的樣式),但ElementEnd
“只是在運行結束時”,並且鍵入的文本將添加到運行中。
這是一個修改過的解決方案(以待處理的粗體樣式為例),似乎適用於所有情況:
private bool IsBoldStylePending { get; set; }
private void RichTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!IsBoldStylePending)
return;
rtb.BeginChange();
Run run = new Run(e.Text, rtb.CaretPosition); // Add the next character with style
run.FontWeight = FontWeights.Bold;
rtb.EndChange();
rtb.CaretPosition = run.ElementEnd; // Keep caret just within the run
IsBoldStylePending = false;
e.Handled = true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.