是否有可能提供一個換行建議給TextBlock ,你可以在HTML做<SHY> (soft hyphen)
或<WBR> (word break)
或 更加複雜,少維護zero-width-space ​
包裝文字
目前的文本塊符話只是因爲它認爲必要, 結束了自動換行像
Stackoverflo
W¯¯
我要的是:
Stackover-
流
或至少:
Stackover
流
如果有推薦的方法來實現所需,請讓我知道。
是否有可能提供一個換行建議給TextBlock ,你可以在HTML做<SHY> (soft hyphen)
或<WBR> (word break)
或 更加複雜,少維護zero-width-space ​
包裝文字
目前的文本塊符話只是因爲它認爲必要, 結束了自動換行像
Stackoverflo
W¯¯
我要的是:
Stackover-
流
或至少:
Stackover
流
如果有推薦的方法來實現所需,請讓我知道。
設置TextBlock.IsHypenationEnabled
爲true居然會做一些類似的東西,但如果你想使用標籤,你可以使用這樣的方法:
/// <summary>
/// Adds break to a TextBlock according to a specified tag
/// </summary>
/// <param name="text">The text containing the tags to break up</param>
/// <param name="tb">The TextBlock we are assigning this text to</param>
/// <param name="tag">The tag, eg <br> to use in adding breaks</param>
/// <returns></returns>
public string WordWrap(string text, TextBlock tb, string tag)
{
//get the amount of text that can fit into the textblock
int len = (int)Math.Round((2 * tb.ActualWidth/tb.FontSize));
string original = text.Replace(tag, "");
string ret = "";
while (original.Length > len)
{
//get index where tag occurred
int i = text.IndexOf(tag);
//get index where whitespace occurred
int j = original.IndexOf(" ");
//does tag occur earlier than whitespace, then let's use that index instead!
if (j > i && j < len)
i = j;
//if we usde index of whitespace, there is no need to hyphenate
ret += (i == j) ? original.Substring(0, i) + "\n" : original.Substring(0, i) + "-\n";
//if we used index of whitespace, then let's remove the whitespace
original = (i == j) ? original.Substring(i + 1) : original.Substring(i);
text = text.Substring(i + tag.Length);
}
return ret + original;
}
這樣你現在可以說:
textBlock1.Text = WordWrap("StackOver<br>Flow For<br>Ever", textBlock1, "<br>");
這個將輸出:
然而,只用IsHyphenated沒有標籤,這將是:
雖然:
textBlock1.Text = WordWrap("StackOver<br>Flow In<br> U", textBlock1, "<br>");
將輸出:
而且IsHyphenated無標籤:
編輯: 在減少字體大小,我發現第一個代碼我張貼不喜歡加入其中的空格發生用戶指定的休息休息。
使用TextFormatter
連同自定義TextSource
來控制文本如何分解和包裝。
您需要從TextSource和您的實現派生類,分析你的內容/串並提供包裝規則,例如尋找你的<wbr>標籤...當你看到一個標籤時,你會返回TextEndOfLine
否則你會返回一個TextCharacters
。
一個例子可能在實施TextSource
幫助是在這裏:
對於一個非常先進的例子來看一下 「AvalonEdit」 也使用它:
如果您不需要豐富的格式,您也可以調查GlyphRun
。
這些例子非常好! +1雖然,必須有一個更簡單的方法來做到這一點。也許是理解一個軟連字符或類似的東西的包裝文本框。 – 2012-07-12 21:27:57
您可以使用RichTextBox,然後只提供適當定義的RTF。 – 2012-07-12 21:46:22
看起來像個好主意,必須找到它的工作原理。 – 2012-07-12 21:51:54
謝謝!這看起來完全像我想要的。在接受之前必須先嚐試一下。 – 2012-07-13 09:21:06
工作良好,只需做兩個小改動:1.將textBlock1替換爲參數tb 2. //獲取發生標記的索引 int i = text.IndexOf(tag); if(i <0) return ret + text; } – 2012-07-16 14:45:05
謝謝,我實際上認爲我已經更新了這個......至於檢查標籤是否存在,如果您僅將它用於需要標籤的文本,則不是必需的,如果您希望所有的TextBlocks都具有此功能,您應該進行自定義控制並覆蓋文本更改屬性... – 2012-07-16 20:42:22