2015年4月23日 星期四

WPF學習筆記 - 4 WPF 控制項 - TextBlock

TextBlock光看名字就知道,就是一個讓你顯示文字的區塊

<TextBlock>This is a TextBlock</TextBlock>

如果字串過長,字會自動被隱藏

<TextBlock Margin="10" Foreground="Red">
    This is a TextBlock control<LineBreak />
    with multiple lines of text.
</TextBlock>

<TextBlock Margin="10" TextTrimming="CharacterEllipsis" Foreground="Green">
    This is a TextBlock control with text that may not be rendered completely, which will be indicated with an ellipsis.
</TextBlock>

<TextBlock Margin="10" TextWrapping="Wrap" Foreground="Blue">
    This is a TextBlock control with automatically wrapped text, using the TextWrapping property.
</TextBlock>

<LineBreak /> : 直接規定這裡要換行,不是很好的作法,較無彈性。
TextTrimming="CharacterEllipsis" : 超過的字會以...代替,如果使用WordEllipsis,會以單字為單位,就不會有一個字突然被切斷的情形發生。
TextWrapping="Wrap" : 視位置自動換行,一定會顯示出所有的字出來。

其他功能:
<Bold></Bold> - 粗體
<Italic></Italic> - 斜體
<Underline></Underline> - 下底線
<Hyperlink RequestNavigate="Hyperlink_RequestNavigate" NavigateUri="https://www.google.com">link</Hyperlink> - 超連結

Backend會多一個Hyperlink_RequestNavigate() method,需要實作它

private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
        System.Diagnostics.Process.Start(e.Uri.AbsoluteUri);
}

<span></span> - 作用與HTML的span有點相像,可以設定許多的屬性,以便管理

<TextBlock Margin="10" TextWrapping="Wrap">
   This <Span FontWeight="Bold">is</Span> a
   <Span Background="Silver" Foreground="Maroon">TextBlock</Span>
   with <Span TextDecorations="Underline">several</Span>
   <Span FontStyle="Italic">Span</Span> elements,
   <Span Foreground="Blue">
       using a <Bold>variety</Bold> of <Italic>styles</Italic>
   </Span>.
</TextBlock>

用C#設格式

public partial class TextBlockCodeBehindSample : Window
{
    public TextBlockCodeBehindSample()
    {
        InitializeComponent();
        TextBlock tb = new TextBlock();
        tb.TextWrapping = TextWrapping.Wrap;
        tb.Margin = new Thickness(10);
        tb.Inlines.Add("An example on ");
        tb.Inlines.Add(new Run("the TextBlock control ") { FontWeight = FontWeights.Bold });
        tb.Inlines.Add("using ");
        tb.Inlines.Add(new Run("inline ") { FontStyle = FontStyles.Italic });
        tb.Inlines.Add(new Run("text formatting ") { Foreground = Brushes.Blue });
        tb.Inlines.Add("from ");
        tb.Inlines.Add(new Run("Code-Behind") { TextDecorations = TextDecorations.Underline });
        tb.Inlines.Add(".");
        this.Content = tb;
    }
}

沒有留言:

張貼留言

[泰國] 芭達雅大城八日遊 Day7、8 - 瑪哈泰寺、Wat Ratchaburana、帕蒙空博碧寺、帕席桑碧寺、Hua Ro market、Chantharakasem National Museum、Amporn Department Store

第七天行程,早上吃飯店早餐,算不錯吃,只是有螞蟻,但吃完沒拉,所以應該還好 吃飽後飽嘟嘟車,一小時 200 泰銖,比自己叫還便宜,終於要來世界遺產之旅了 第一站:瑪哈泰寺,應該是大城最有名的景點了,入門票大人 120 ,小孩免費,其實不便宜 大城指標性景點...