《WPF程序设计指南》读书笔记——第4章 按钮与其他控件

1.Button类

using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Input;
using System.Windows.Controls;

namespace LY.ClickTheButton
{
    public class ClickTheButton:Window
    {
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new ClickTheButton());
        }
        public ClickTheButton()
        {
            Title = "Click the Butten!";
            Button btn=new Button();
            //下划线作用是按下Alt健时,C字母下会出现下划线
            //表明Alt+C为此Button的快捷键            
            btn.Content = "_Click me,Please!";
            //设置此按钮为焦点
            btn.Focus();
            //设置为默认按钮
            btn.IsDefault = true;
            //设置为取消按钮
            btn.IsCancel = true;
            //点击模式为悬停即触发事件
            btn.ClickMode = ClickMode.Hover;
            //设置文字在按钮内的位置
            btn.HorizontalContentAlignment = HorizontalAlignment.Left;
            btn.VerticalContentAlignment = VerticalAlignment.Bottom;
            //设置按钮在窗体中的位置
            btn.HorizontalAlignment = HorizontalAlignment.Stretch;
            //默认为Stretch
            btn.VerticalAlignment = VerticalAlignment.Center;
            //设置外边缘大小
            btn.Margin = new Thickness(48);
            //设置内边缘大小(即文字和边框大小)
            btn.Padding = new Thickness(48,48,96,96);
            btn.FontSize = 48;
            btn.FontFamily = new FontFamily("Times New Roman");
            btn.Click += ButtonOnClick;
            Content = btn;
        }
        public void ButtonOnClick(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("The button has been clicked!", Title);
        }
    }
}

2.在按钮上显示文本(使用TextBlock类) 

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

namespace LY.FormatTheButton
{
    public class FormatTheButton : Window
    {
        Run runButton;

        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new FormatTheButton());
        }
        public FormatTheButton()
        {
            Title = "Format the Button";

            Button btn = new Button();
            btn.HorizontalAlignment = HorizontalAlignment.Center;
            btn.VerticalAlignment = VerticalAlignment.Center;
            btn.MouseEnter += ButtonOnMouseEnter;
            btn.MouseLeave += ButtonOnMouseLeave;
            Content = btn;

            // 创建TextBlock对象,将其设为按钮的内容
            TextBlock txtblk = new TextBlock();
            txtblk.FontSize = 24;
            txtblk.TextAlignment = TextAlignment.Center;
            btn.Content = txtblk;
            
            // 在TextBlock中加入格式化文本
            txtblk.Inlines.Add(new Italic(new Run("Click")));
            txtblk.Inlines.Add(" the ");
            txtblk.Inlines.Add(runButton = new Run("button"));
            txtblk.Inlines.Add(new LineBreak());
            txtblk.Inlines.Add("to launch the ");
            txtblk.Inlines.Add(new Bold(new Run("rocket")));
        }
        void ButtonOnMouseEnter(object sender, MouseEventArgs args)
        {
            runButton.Foreground = Brushes.Red;
        }
        void ButtonOnMouseLeave(object sender, MouseEventArgs args)
        {
            runButton.Foreground = SystemColors.ControlTextBrush;
        }
    }
}

  1)TextBlock类在“System.Windows.Controls"命名空间里,是用于显示少量流内容的轻量控件。

  2)在”System.Windows.Documents“命名空间下,Inlines是内联文本元素的集合;Run类用于显示一个无格式文本;Bold类用于显示粗体;Italic类用于显示斜体;LineBreak类用于显示换行;上述流文档可以很方便地在一个textblock中显示不同格式的文本。

  3)进一步参考:http://www.cnblogs.com/jacksonyin/archive/2008/03/17/1109416.html 

3.在按钮上显示图像(使用Image类) 

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace LY.ImageTheButton
{
    public class ImageTheButton : Window
    {
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new ImageTheButton());
        }
        public ImageTheButton()
        {
            Title = "Image the Button";

            Uri uri = new Uri("pack://application:,,/munch.png");
            BitmapImage bitmap = new BitmapImage(uri);

            Image img = new Image();
            img.Source = bitmap;
            img.Stretch = Stretch.None;

            Button btn = new Button();
            btn.Content = img;
            btn.HorizontalAlignment = HorizontalAlignment.Center;
            btn.VerticalAlignment = VerticalAlignment.Center;

            Content = btn;
        }
    }
}

  1)通过”添加-现有项-添加“将图片加入工程,再通过”文件属性-生成操作-resourse"可以将图片资源内嵌到exe或dll文件中。

  2)可以通过“Uri uri = new Uri("pack://application:,,/photo.png"的方式访问内嵌的资源。

4.将命令绑定给按钮(Command属性和CommandBinding类)

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace LY.CommandTheButton
{
    public class CommandTheButton : Window
    {
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new CommandTheButton());
        }
        public CommandTheButton()
        {
            Title = "Command the Button";

            //将此命令绑定到事件处理器
            Button btn = new Button();
            btn.HorizontalAlignment = HorizontalAlignment.Center;
            btn.VerticalAlignment = VerticalAlignment.Center;
            btn.Command = ApplicationCommands.Paste;
            btn.Content = ApplicationCommands.Paste.Text;
            Content = btn;

            // 将命令绑定到事件处理器
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Paste,
                                PasteOnExecute, PasteCanExecute));
        }
        void PasteOnExecute(object sender, ExecutedRoutedEventArgs args)
        {
            Title = Clipboard.GetText();
        }
        void PasteCanExecute(object sender, CanExecuteRoutedEventArgs args)
        {
            args.CanExecute = Clipboard.ContainsText();
        }
        protected override void OnMouseDown(MouseButtonEventArgs args)
        {
            base.OnMouseDown(args);
            Title = "Command the Button";
        }
    }
}

  1)按钮既可以通过事件触发命令,也可以通过Command属性,或CommandBindings集合将命令绑定到按钮。

  2)绑定的命令可以是ApplicationCommands类、ComponentCommands类、MediaCommands类、NavigationCommands类、EditingCommands类的静态属性;前四个在System.Windows.Input命名空间,最后一个在System.Windows.Documents命名空间。

5.其他类型的常用控件(CheckBox/RadioButton/Label/TextBox/RichTextBox

5.1  ToggleButton/CheckBox

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace LY.ToggleTheButton
{
    public class ToggleTheButton:Window
    {
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new ToggleTheButton());
        }
        public ToggleTheButton()
        {
            Title = "Toggle The Button";
            //ToggleButton是CheckBox、RadioButton的基类
            //ToggleButton btn = new ToggleButton();
            CheckBox btn = new CheckBox();
            btn.Content = "Can _Resize";
            btn.HorizontalAlignment = HorizontalAlignment.Center;
            btn.VerticalAlignment = VerticalAlignment.Center;
            //指定IsChecked是否有三种状态True、False、Null(不确定状态)
            btn.IsThreeState = false;
            btn.IsChecked = (ResizeMode == ResizeMode.CanResize);
            btn.Checked += ButtonOnChecked;
            btn.Unchecked += ButtonOnChecked;
            Content = btn;
        }
        void ButtonOnChecked(object sender, RoutedEventArgs e)
        {
            ToggleButton btn = sender as ToggleButton;
            ResizeMode = (bool)btn.IsChecked ? ResizeMode.CanResize : ResizeMode.NoResize;
        }
    }    
}

 5.2  数据绑定 

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Data;

namespace LY.BindTheButton
{
    public class BindTheButton:Window
    {
        [STAThread]
        public static void Main()
        {
            new Application().Run(new BindTheButton());
        }
        public BindTheButton()
        {
            Title = "Bind The Button";
            ToggleButton btn = new ToggleButton();
            btn.Content = "Make _Topmost";
            btn.HorizontalAlignment = HorizontalAlignment.Center;
            btn.VerticalAlignment = VerticalAlignment.Center;
            //数据绑定
            //btn.SetBinding(ToggleButton.IsCheckedProperty, "Topmost");
            //btn.DataContext = this;b
            //更好的数据绑定方法
            Binding bind = new Binding("Topmost");
            bind.Source = this;
            btn.SetBinding(ToggleButton.IsCheckedProperty, bind);
            Content = btn;
            //给按钮设定一个提示项
            ToolTip tip = new ToolTip();
            tip.Content = "Please Click";
            btn.ToolTip = tip;
            //Label控件
            //Label lb = new Label();
            //lb.Content = "File_Name";
        }
    }
}

 5.3  Frame类\TextBox

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Data;

namespace LY.NavigateTheWeb
{
    public class NavigateTehWeb:Window
    {
        Frame frm;
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            try
            {
                app.Run(new NavigateTehWeb());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public NavigateTehWeb()
        {
            Title = "Navigate the web";
            frm = new Frame();
            Content = frm;
            Loaded += OnWindowLoaded;
        }
        void OnWindowLoaded(object sender, RoutedEventArgs e)
        {
            UriDialog dlg = new UriDialog();
            dlg.Owner = this;
            dlg.Text = "Http://";
            dlg.ShowDialog();
            //如果用Content属性,会直接显现用户输入的Uri文本
            //frm.Content = new Uri(dlg.Text);
            //Source属性可以打开网页
            frm.Source = new Uri(dlg.Text); 
        }
    }
}

  

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Data;

namespace LY.NavigateTheWeb
{
    public class UriDialog:Window
    {
        TextBox textbox;
        public UriDialog()
        {
            Title = "Enter a Uri";
            //对话框通常不出现在任务栏
            ShowInTaskbar = false;
            //对话框通常大小缩放到和内容一样
            SizeToContent = SizeToContent.WidthAndHeight;
            //对话框通常设定位ToolWindow
            WindowStyle = WindowStyle.ToolWindow;
            WindowStartupLocation = WindowStartupLocation.CenterOwner;
            textbox = new TextBox();
            textbox.Margin = new Thickness(48);
            //设定文本框接受回车,即允许多行编辑
            textbox.AcceptsReturn = true;
            Content = textbox;
            textbox.Focus();
        }
        public string Text
        {
            get
            {
                return textbox.Text;
            }
            set
            {
                textbox.Text = value;
                //设定光标起始位置
                textbox.SelectionStart = textbox.Text.Length;
            }
        }
        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            if (e.Key == Key.Enter)
                Close();
        }

    }
}

 5.4  TextBox中文字的读取和保存

using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Input;
using System.Windows.Controls;
using System.IO;

namespace LY.EditSomeText
{
    public class EditSomeText:Window
    {
        static string strFileName = Path.Combine(Environment.GetFolderPath(
            Environment.SpecialFolder.LocalApplicationData),
            "LY\\EditSomeText\\EditSomeText.txt");
        TextBox txtbox;
        [STAThread]
        public static void Main()
        {
            new Application().Run(new EditSomeText());
        }
        public EditSomeText()
        {
            Title = "Edit Some Text";
            txtbox = new TextBox();
            txtbox.AcceptsReturn = true;
            //设定换行方式
            txtbox.TextWrapping = TextWrapping.Wrap;
            txtbox.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            txtbox.KeyDown+=TxtBoxOnKeyDown;
            Content = txtbox;
            try
            {
                txtbox.Text = File.ReadAllText(strFileName);
            }
            catch
            {
            }
            //设定光标位置
            txtbox.CaretIndex = txtbox.Text.Length;
            txtbox.Focus();
        }
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                Directory.CreateDirectory(Path.GetDirectoryName(strFileName));
                File.WriteAllText(strFileName, txtbox.Text);
            }
            catch (Exception ex)
            {
                MessageBoxResult result = MessageBox.Show("文件不能被保持: " + ex.Message +
                    "关闭程序?", Title, MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
                e.Cancel = (result == MessageBoxResult.No);
            }
        }
        void TxtBoxOnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.F5)
            {
                txtbox.SelectedText = DateTime.Now.ToString();
                txtbox.CaretIndex = txtbox.SelectionStart + txtbox.SelectionLength;
            }
        }
    }
}

  5.5  RichTextBox中文字的读取和保存

using Microsoft.Win32;
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

namespace LY.EditSomeRichText
{
    public class EditSomeRichText : Window
    {
        RichTextBox txtbox;
        string strFilter = 
            "Document Files(*.xaml)|*.xaml|All files (*.*)|*.*";

        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new EditSomeRichText());
        }
        public EditSomeRichText()
        {
            Title = "Edit Some Rich Text";

            txtbox = new RichTextBox();
            txtbox.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            Content = txtbox;

            txtbox.Focus();
        }
        protected override void OnPreviewTextInput(TextCompositionEventArgs args)
        {
            if (args.ControlText.Length > 0 && args.ControlText[0] == '\x0F')
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.CheckFileExists = true;
                dlg.Filter = strFilter;

                if ((bool)dlg.ShowDialog(this))
                {
                    FlowDocument flow = txtbox.Document;
                    TextRange range = new TextRange(flow.ContentStart, 
                                                    flow.ContentEnd);
                    Stream strm = null;

                    try
                    {
                        strm = new FileStream(dlg.FileName, FileMode.Open);
                        range.Load(strm, DataFormats.Xaml);
                    }
                    catch (Exception exc)
                    {
                        MessageBox.Show(exc.Message, Title);
                    }
                    finally
                    {
                        if (strm != null)
                            strm.Close();
                    }
                }

                args.Handled = true;
            }
            if (args.ControlText.Length > 0 && args.ControlText[0] == '\x13')
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = strFilter;

                if ((bool)dlg.ShowDialog(this))
                {
            //Document属性取得流 FlowDocument flow = txtbox.Document;
            //用TextRange将流文档包围起来 TextRange range = new TextRange(flow.ContentStart, flow.ContentEnd); Stream strm = null; try { strm = new FileStream(dlg.FileName, FileMode.Create); range.Save(strm, DataFormats.Xaml); } catch (Exception exc) { MessageBox.Show(exc.Message, Title); } finally { if (strm != null) strm.Close(); } } args.Handled = true; } base.OnPreviewTextInput(args); } } }

 

posted @ 2013-08-19 00:35  小p  阅读(579)  评论(1编辑  收藏  举报