【发布时间】:2021-11-17 18:41:56
【问题描述】:
我需要将部分字符串加粗。由于 TextBlock 不支持将部分文本加粗,因此我转而使用 RichTextBox。现在,我希望我的 RichTextBox 限制为单行,如果内容较长以适合单行,它应该使用字符省略号来截断字符串。以下是我绑定到 RichTextBox 的 ViewModel,
public class SearchSuggestionViewModel : BindableBase, IComparable<SearchSuggestionViewModel>
{
private Suggestion _suggestion;
private string m_DocumentXaml = string.Empty;
public SearchSuggestionViewModel(Suggestion suggestion)
{
_suggestion = suggestion;
if (string.IsNullOrEmpty(suggestion.Text))
return;
string searchText = _suggestion.Text;
FlowDocument document = new FlowDocument();
Paragraph paragraph = new Paragraph();
Run run = new Run();
while (searchText.Contains("<b>"))
{
string initialText = searchText.Substring(0, searchText.IndexOf("<b>"));
run.Text = initialText;
paragraph.Inlines.Add(run);
searchText = searchText.Substring(searchText.IndexOf("<b>") + "<b>".Length);
string boldText = searchText;
if (searchText.Contains("</b>"))
boldText = searchText.Substring(0, searchText.IndexOf("</b>"));
run = new Run();
run.FontWeight = FontWeights.Bold;
run.Text = boldText;
paragraph.Inlines.Add(run);
searchText = searchText.Substring(searchText.IndexOf("</b>") + "</b>".Length);
}
run = new Run();
run.Text = searchText;
paragraph.Inlines.Add(run);
document.Blocks.Add(paragraph);
DocumentXaml = XamlWriter.Save(document);
}
public string Id
{
get
{
return _suggestion.Id;
}
}
public string SearchSuggestionText
{
get
{
if (!string.IsNullOrWhiteSpace( _suggestion.Text))
return _suggestion.Text.Replace("<b>", "").Replace("</b>", "");
return string.Empty;
}
}
/// <summary>
/// The text from the FsRichTextBox, as a XAML markup string.
/// </summary>
public string DocumentXaml
{
get
{
return m_DocumentXaml;
}
set
{
SetProperty(ref m_DocumentXaml, value, nameof(DocumentXaml));
}
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is SearchSuggestionViewModel))
return false;
SearchSuggestionViewModel otherTag = (SearchSuggestionViewModel)obj;
if (SearchSuggestionText.Equals(otherTag.SearchSuggestionText))
return true;
return false;
}
public int CompareTo(SearchSuggestionViewModel compareSearchSuggestionViewModel)
{
// A null value means that this object is greater.
if (compareSearchSuggestionViewModel == null)
return 1;
else
return this.SearchSuggestionText.CompareTo(compareSearchSuggestionViewModel.SearchSuggestionText);
}
public override string ToString()
{
return _suggestion.Text;
}
}
关于如何在行尾之前获得字符省略号的任何建议。
问候, 奥马尔
【问题讨论】:
-
“由于 TextBlock 不支持部分文本以粗体显示”:TextBlock 有一个 TextBlock.Inlines 属性,您可以使用它来组成运行和段落的显示文本类似于 RichTextBox 的元素。因此,如果您不关心文本输入,您也可以在 TextBlock 中使用一些更复杂的文本格式。
标签: c# wpf richtextbox