背水一戰 Windows 10 (28) - 控件(文本類): TextBox, PasswordBox


[源碼下載]


背水一戰 Windows 10 (28) - 控件(文本類): TextBox, PasswordBox



作者:webabcd


介紹
背水一戰 Windows 10 之 控件(文本類)

  • TextBox
  • PasswordBox



示例
1、TextBox 的示例 1
Controls/TextControl/TextBoxDemo1.xaml

<Page
    x:Class="Windows10.Controls.TextControl.TextBoxDemo1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.Controls.TextControl"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="10 0 10 10">

            <!--
                TextBox - 文本輸入框
                    Text - 文本值
                    Header - 可以設置一個純文本,不能命中測試,空 Header 的話不會占用任何空間
                    HeaderTemplate - 可以將 Header 設置為任何 xaml,且支持命中測試
                    MaxLength - 最大字符數(默認是 0 代表無限制)
                    PlaceholderText - 占位符水印
                    AcceptsReturn - 是否允許輸入和顯示回車符和換行符
                    IsSpellCheckEnabled - 是否開啟拼寫檢查功能
                    IsTextPredictionEnabled - 是否開啟輸入預測功能
                    DesiredCandidateWindowAlignment - IME 的對齊方式(IME - Input Method Editor; SIP - Soft Input Panel)
                        Default - 當使用硬鍵盤時,IME 會隨着光標移動;當使用軟鍵盤時,IME 停靠於 SIP
                        BottomEdge - 當使用硬鍵盤時,IME 會與文本編輯控件的底部邊緣和左側對齊(經測試僅微軟輸入法有效,也許是第三方輸入法沒有實現某個接口);當使用軟鍵盤時,IME 停靠於 SIP
            -->
            
            <TextBox Name="textBox1" Margin="5" Height="100"
                     Header="文本框"
                     PlaceholderText="enter your text"
                     MaxLength="32"
                     TextWrapping="Wrap"
                     AcceptsReturn="True"
                     IsSpellCheckEnabled="False"
                     IsTextPredictionEnabled="True"
                     DesiredCandidateWindowAlignment="Default" />

            <TextBox Name="textBox2" Margin="5"
                     Text="textBox2"
                     TextAlignment="Center"
                     IsReadOnly ="True">
                <TextBox.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock Text="文本框" Foreground="Red" />
                    </DataTemplate>
                </TextBox.HeaderTemplate>
            </TextBox>


            <!--
                InputScope - 指定 SIP(Soft Input Panel)的類型
            -->
            <TextBox Name="textBox3" Margin="5" InputScope="Number" />

            <!--
                在 CodeBehind 端設置此 TextBox 的 InputScope
            -->
            <TextBox Name="textBox4" Margin="5" />


            <!--
                TextWrapping - 換行方式
                    NoWrap - 不換行
                    Wrap - 換行,必要時可截斷單詞
                    WrapWholeWords - 換行,但是絕不截斷單詞,即使單詞可能會顯示不全(經測試無效,TextBlock 是支持的)
            -->
            <TextBox Width="100" HorizontalAlignment="Left" Text="abcdefghijklmnopq www" Margin="5" TextWrapping="NoWrap" />
            <TextBox Width="100" HorizontalAlignment="Left" Text="abcdefghijklmnopq www" Margin="5" TextWrapping="Wrap" />


            <!--
                 TextAlignment - 文本的水平對齊方式
                    Center, Left(默認值), Right, Justify(兩端對齊,經測試無效,TextBlock 是支持的)
            -->
            <TextBox Text="i am a &quot;TextBlock&quot;" Margin="5" TextAlignment="Right" />
            
        </StackPanel>
    </Grid>
</Page>

Controls/TextControl/TextBoxDemo1.xaml.cs

/*
 * TextBox - 文本輸入框(繼承自 Control, 請參見 /Controls/BaseControl/ControlDemo/)
 */

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;

namespace Windows10.Controls.TextControl
{
    public sealed partial class TextBoxDemo1 : Page
    {
        public TextBoxDemo1()
        {
            this.InitializeComponent();

            this.Loaded += TextBoxDemo1_Loaded;
        }

        private void TextBoxDemo1_Loaded(object sender, RoutedEventArgs e)
        {
            // 在 CodeBehind 端設置 TextBox 的 InputScope
            InputScope scope = new InputScope();
            InputScopeName name = new InputScopeName();

            name.NameValue = InputScopeNameValue.ChineseFullWidth;
            scope.Names.Add(name);

            textBox4.InputScope = scope;
        }
    }
}


2、TextBox 的示例 2
Controls/TextControl/TextBoxDemo2.xaml

<Page
    x:Class="Windows10.Controls.TextControl.TextBoxDemo2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.Controls.TextControl"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="10 0 10 10">

            <!--用於顯示 Segoe UI Emoji 字符-->
            <TextBox Name="textBox1" Margin="5" TextWrapping="Wrap" />

            <TextBox Name="textBox2" Margin="5" />
            <TextBlock Name="textBlock2" Margin="5" />

            <TextBox Name="textBox3" Margin="5" />
            <ScrollViewer Margin="5" Height="300">
                <TextBlock Name="textBlock3" />
            </ScrollViewer>

        </StackPanel>
    </Grid>
</Page>

Controls/TextControl/TextBoxDemo2.xaml.cs

/*
 * TextBox - 文本輸入框(繼承自 Control, 請參見 /Controls/BaseControl/ControlDemo/)
 *     IsColorFontEnabled - 是否以彩色方式顯示 Segoe UI Emoji 之類的字符(默認值是 true) 
 *     SelectAll() - 選中全部內容(先要獲取焦點后,才能做這個操作)
 *     Select(int start, int length) - 選中指定范圍的內容(先要獲取焦點后,才能做這個操作)
 *     SelectedText - 選中的內容
 *     SelectionStart - 選中內容的起始位置
 *     SelectionLength - 選中內容的字符數
 *     SelectionHighlightColor - 選中文本的顏色
 *     PreventKeyboardDisplayOnProgrammaticFocus - 通過 FocusState.Programmatic 讓 TextBox 獲取焦點時,是否不顯示軟鍵盤
 *     GetLinguisticAlternativesAsync() - 獲取輸入法編輯器 (IME) 窗口中的候選詞列表(經測試僅微軟輸入法有效,也許是第三方輸入法沒有實現某個接口)
 *     GetRectFromCharacterIndex(int charIndex, bool trailingEdge) - 獲取指定字符的邊緣位置的 Rect 對象
 *         charIndex - 字符的位置
 *         trailingEdge - false 代表前邊緣(左邊緣),true 代表后邊緣(右邊緣)
 *
 *     TextBox 的相關事件的說明詳見代碼部分的注釋
 */

using System;
using System.Text;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace Windows10.Controls.TextControl
{
    public sealed partial class TextBoxDemo2 : Page
    {
        public TextBoxDemo2()
        {
            this.InitializeComponent();

            this.Loaded += TextBoxDemo2_Loaded;
        }

        private void TextBoxDemo2_Loaded(object sender, RoutedEventArgs e)
        {
            // 顯示 Segoe UI Emoji 字符
            StringBuilder strContect = new StringBuilder();
            for (int code = 0x1F600; code < 0x1F6C6; code++)
            {
                strContect.Append(char.ConvertFromUtf32(code));
            }
            // 是否以彩色方式顯示 Segoe UI Emoji 之類的字符(默認值是 true) 
            textBox1.IsColorFontEnabled = true;
            textBox1.Text = strContect.ToString();



            textBox2.Text = "123456";
            // 當通過 FocusState.Programmatic 讓 textBox2 獲取焦點時,不顯示軟鍵盤
            textBox2.PreventKeyboardDisplayOnProgrammaticFocus = true;
            // 通過 FocusState.Programmatic 讓 textBox2 獲取焦點
            textBox2.Focus(FocusState.Programmatic);
            // 獲取焦點后,才能 Select() 或 SelectAll()
            textBox2.Select(1, 4); // SelectAll() - 選中全部
            textBox2.SelectionHighlightColor = new SolidColorBrush(Colors.Orange);

            textBlock2.Text = "SelectedText: " + textBox2.SelectedText;
            textBlock2.Text += Environment.NewLine;
            textBlock2.Text += "SelectionStart: " + textBox2.SelectionStart;
            textBlock2.Text += Environment.NewLine;
            textBlock2.Text += "SelectionLength: " + textBox2.SelectionLength;
            textBlock2.Text += Environment.NewLine;

            // 獲取第 1 個字符的左邊緣的 Rect 對象
            textBlock2.Text += "GetRectFromCharacterIndex(0, false): " + textBox2.GetRectFromCharacterIndex(0, false).ToString();
            textBlock2.Text += Environment.NewLine;
            // 獲取第 1 個字符的右邊緣的 Rect 對象
            textBlock2.Text += "GetRectFromCharacterIndex(0, true): " + textBox2.GetRectFromCharacterIndex(0, true).ToString();

            

            // TextBox 的相關事件的說明及演示如下

            // 當文本發生變化時觸發的事件
            textBox3.TextChanging += TextBox3_TextChanging;
            // 當文本發生變化后觸發的事件
            textBox3.TextChanged += TextBox3_TextChanged;

            // 選中的文本發生變化后觸發的事件
            textBox3.SelectionChanged += TextBox3_SelectionChanged;
            // 在 TextBox 中做粘貼操作時觸發的事件
            textBox3.Paste += TextBox3_Paste;
            // 在 TextBox 中打開上下文菜單時觸發的事件(觸摸屏長按或鼠標右鍵)
            textBox3.ContextMenuOpening += TextBox3_ContextMenuOpening;

            // 在打開、更新或關閉輸入法編輯器 (IME) 窗口時觸發的事件(經測試僅微軟輸入法有效,也許是第三方輸入法沒有實現某個接口)
            textBox3.CandidateWindowBoundsChanged += TextBox3_CandidateWindowBoundsChanged;
            // 當通過輸入方法編輯器 (IME) 組成的文本出現變化時觸發的事件
            textBox3.TextCompositionChanged += TextBox3_TextCompositionChanged;
            // 當用戶開始通過輸入方法編輯器 (IME) 組成文本時觸發的事件
            textBox3.TextCompositionStarted += TextBox3_TextCompositionStarted;
            // 當用戶停止通過輸入方法編輯器 (IME) 組成文本時觸發的事件
            textBox3.TextCompositionEnded += TextBox3_TextCompositionEnded;
        }

        private void TextBox3_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
        {
            textBlock3.Text += "TextChanging: " + textBox3.Text;
            textBlock3.Text += Environment.NewLine;
        }

        private void TextBox3_TextChanged(object sender, TextChangedEventArgs e)
        {
            textBlock3.Text += "TextChanged: " + textBox3.Text;
            textBlock3.Text += Environment.NewLine;
        }

        private void TextBox3_SelectionChanged(object sender, RoutedEventArgs e)
        {
            textBlock3.Text += "SelectionChanged: " + textBox3.SelectedText;
            textBlock3.Text += Environment.NewLine;
        }

        private async void TextBox3_Paste(object sender, TextControlPasteEventArgs e)
        {
            await new MessageDialog("禁用粘貼").ShowAsync();

            // 將路由事件設置為已處理,從而禁用粘貼功能
            e.Handled = true;
        }

        private void TextBox3_ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            textBlock3.Text += "ContextMenuOpening";
            textBlock3.Text += Environment.NewLine;
        }

        private void TextBox3_CandidateWindowBoundsChanged(TextBox sender, CandidateWindowBoundsChangedEventArgs args)
        {
            // CandidateWindowBoundsChangedEventArgs.Bounds - 獲取 IME 窗口的 Rect 對象
            textBlock3.Text += "CandidateWindowBoundsChanged: " + args.Bounds.ToString();
            textBlock3.Text += Environment.NewLine;
        }

        private async void TextBox3_TextCompositionChanged(TextBox sender, TextCompositionChangedEventArgs args)
        {
            // TextCompositionChangedEventArgs.StartIndex - 通過 IME 組成的文本的起始位置
            // TextCompositionChangedEventArgs.Length - 通過 IME 組成的文本的長度
            textBlock3.Text += $"TextCompositionChanged StartIndex:{args.StartIndex}, Length:{args.Length}";
            textBlock3.Text += Environment.NewLine;


            // GetLinguisticAlternativesAsync() - 獲取輸入法編輯器 (IME) 窗口中的候選詞列表(經測試僅微軟輸入法有效,也許是第三方輸入法沒有實現某個接口)
            var candidateWords = await textBox3.GetLinguisticAlternativesAsync();
            textBlock3.Text += "candidate words: " + string.Join(",", candidateWords); ;
            textBlock3.Text += Environment.NewLine;
        }

        private void TextBox3_TextCompositionStarted(TextBox sender, TextCompositionStartedEventArgs args)
        {
            // TextCompositionStartedEventArgs.StartIndex - 通過 IME 組成的文本的起始位置
            // TextCompositionStartedEventArgs.Length - 通過 IME 組成的文本的長度
            textBlock3.Text += $"TextCompositionStarted StartIndex:{args.StartIndex}, Length:{args.Length}";
            textBlock3.Text += Environment.NewLine;
        }

        private void TextBox3_TextCompositionEnded(TextBox sender, TextCompositionEndedEventArgs args)
        {
            // TextCompositionEndedEventArgs.StartIndex - 通過 IME 組成的文本的起始位置
            // TextCompositionEndedEventArgs.Length - 通過 IME 組成的文本的長度
            textBlock3.Text += $"TextCompositionEnded StartIndex:{args.StartIndex}, Length:{args.Length}";
            textBlock3.Text += Environment.NewLine;
        }
    }
}


3、PasswordBox 的示例
Controls/TextControl/PasswordBoxDemo.xaml

<Page
    x:Class="Windows10.Controls.TextControl.PasswordBoxDemo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.Controls.TextControl"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="10 0 10 10">
            
            <!--
                PasswordBox - 密碼輸入框
                    Password - 密碼值
                    PasswordChar - 密碼框所顯示顯示的密碼替代字符。默認值為“●”
                    IsPasswordRevealButtonEnabled - 是否顯示“顯示密碼明文”按鈕(棄用了)
                    PasswordRevealMode - 密碼顯示方式
                        Peek - 密文顯示,按下“顯示密碼明文”按鈕時顯示明文(默認值)
                        Hidden - 密文顯示,“顯示密碼明文”按鈕不可見
                        Visible - 明文顯示,“顯示密碼明文”按鈕不可見
                    Header - 可以設置一個純文本,不能命中測試,空 Header 的話不會占用任何空間
                    HeaderTemplate - 可以將 Header 設置為任何 xaml,且支持命中測試
                    MaxLength - 最大字符數(默認是 0 代表無限制)
                    PlaceholderText - 占位符水印
            -->
            
            <PasswordBox Name="passwordBox1" Width="200" Margin="5" HorizontalAlignment="Left" 
                         Header="密碼"
                         PlaceholderText="enter your password"
                         MaxLength="6" 
                         PasswordChar="@"
                         PasswordRevealMode="Peek" />


            <PasswordBox Name="passwordBox2" Width="200" Margin="5" HorizontalAlignment="Left">
                <PasswordBox.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock Text="密碼" Foreground="Red" />
                    </DataTemplate>
                </PasswordBox.HeaderTemplate>
            </PasswordBox>

            <TextBlock Name="textBlock" Margin="5" />

        </StackPanel>
    </Grid>
</Page>

Controls/TextControl/PasswordBoxDemo.xaml.cs

/*
 * PasswordBox - 密碼輸入框(繼承自 Control, 請參見 /Controls/BaseControl/ControlDemo/)
 *     Password - 密碼值
 *     SelectAll() - 選中 PasswordBox 中的所有字符(先要獲取焦點后,才能做這個操作)
 *     SelectionHighlightColor - 選中文本的顏色
 *     PreventKeyboardDisplayOnProgrammaticFocus - 通過 FocusState.Programmatic 讓 PasswordBox 獲取焦點時,是否不顯示軟鍵盤
 *     PasswordChanged - Password 屬性值發生變化時觸發的事件
 *     Paste - 在 PasswordBox 中做粘貼操作時觸發的事件
 *     ContextMenuOpening - 在 PasswordBox 中打開上下文菜單時觸發的事件(觸摸屏長按或鼠標右鍵)
 */

using System;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace Windows10.Controls.TextControl
{
    public sealed partial class PasswordBoxDemo : Page
    {
        public PasswordBoxDemo()
        {
            this.InitializeComponent();

            this.Loaded += PasswordBoxDemo_Loaded;
        }

        private void PasswordBoxDemo_Loaded(object sender, RoutedEventArgs e)
        {
            passwordBox2.Password = "123456";

            // 當通過 FocusState.Programmatic 讓 passwordBox2 獲取焦點時,不顯示軟鍵盤
            passwordBox2.PreventKeyboardDisplayOnProgrammaticFocus = true;
            // 通過 FocusState.Programmatic 讓 passwordBox2 獲取焦點
            passwordBox2.Focus(FocusState.Programmatic);

            passwordBox2.SelectAll(); // 先要獲取焦點后,才能做這個操作
            passwordBox2.SelectionHighlightColor = new SolidColorBrush(Colors.Orange);

            passwordBox2.PasswordChanged += (x, y) =>
            {
                textBlock.Text = passwordBox2.Password;
            };

            passwordBox2.Paste += async (x, y) =>
            {
                await new MessageDialog("禁用粘貼").ShowAsync();

                // 將路由事件設置為已處理,從而禁用粘貼功能
                y.Handled = true;
            };

            passwordBox2.ContextMenuOpening += (x, y) =>
            {
                // 觸發條件:觸摸屏長按或鼠標右鍵 
            };
        }
    }
}



OK
[源碼下載]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM