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);
}
}
}

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

  1. 【WPF学习】第六十五章 创建无外观控件

    用户控件的目标是提供增补控件模板的设计表面,提供一种定义控件的快速方法,代价是失去了将来的灵活性.如果喜欢用户控件的功能,但需要修改使其可视化外观,使用这种方法就有问题了.例如,设想希望使用相同的颜色 ...

  2. css权威指南读书笔记-第10章浮动和定位

    这一章看了之后真是豁然开朗,之前虽然写了圣杯布局和双飞翼布局,有些地方也是模糊的,现在打算总结之后再写一遍. 以下都是从<css权威指南>中摘抄的我认为很有用的说明. 浮动元素 一个元素浮 ...

  3. 《Javascript高级程序设计》读书笔记(1-3章)

    第一章 JavaScript简介 1.1 JavaScript简史 略 1.2 JavaScript实现 虽然 JavaScript 和 ECMAScript 通常都被人们用来表达相同的含义,但 Ja ...

  4. JavaScript权威指南读书笔记【第一章】

    第一章 JavaScript概述 前端三大技能: HTML: 描述网页内容 CSS: 描述网页样式 JavaScript: 描述网页行为 特点:动态.弱类型.适合面向对象和函数式编程的风格 语法源自J ...

  5. 《JavaScript高级程序设计》 - 读书笔记 - 第5章 引用类型

    5.1 Object 类型 对象是引用类型的实例.引用类型是一种数据结构,用于将数据和功能组织在一起. 新对象是使用new操作符后跟一个构造函数来创建的.构造函数本身就是一个函数,只不过该函数是出于创 ...

  6. 《JavaScript高级程序设计》 - 读书笔记 - 第4章 变量、作用域和内存问题

    4.1 基本类型和引用类型的值 JavaScript变量是松散类型的,它只是保存特定值的一个名字而已. ECMAScript变量包含两种数据类型的值:基本类型值和引用类型值.基本类型值指的是简单的数据 ...

  7. 《Linux程序设计》--读书笔记---第十三章进程间通信:管道

    管道:进程可以通过它交换更有用的数据. 我们通常是把一个进程的输出通过管道连接到另一个进程的输入: 对shell命令来说,命令的连接是通过管道字符来完成的: cmd1    |     cmd2 sh ...

  8. 《Visual C++ 程序设计》读书笔记 ----第8章 指针和引用

    1.&取地址:*取内容. 2.指针变量“++”“--”,并不是指针变量的值加1或减1,而是使指针变量指向下一个或者上一个元素. 3.指针运算符*与&的优先级相同,左结合:++,--,* ...

  9. 《Linux内核设计与实现》第八周读书笔记——第四章 进程调度

    <Linux内核设计与实现>第八周读书笔记——第四章 进程调度 第4章 进程调度35 调度程序负责决定将哪个进程投入运行,何时运行以及运行多长时间,进程调度程序可看做在可运行态进程之间分配 ...

随机推荐

  1. Android(java)学习笔记71:生产者和消费者之等待唤醒机制

    1. 首先我们根据梳理我们之前Android(java)学习笔记70中关于生产者和消费者程序思路: 2. 下面我们就要重点介绍这个等待唤醒机制: (1)第一步:还是先通过代码体现出等待唤醒机制 pac ...

  2. eclipse中自动生成javadoc文档

    使用eclipse生成文档(javadoc)主要有三种方法:  1,在项目列表中按右键,选择Export(导出),然后在Export(导出)对话框中选择java下的javadoc,提交到下一步.  在 ...

  3. jquery ajax 后台和前台数据交互 C#

    <input type="button" id="updateInfo" value="更改货载重量" /> <div i ...

  4. ResponseBody的使用

    使用Spring的@ResponseBody有时还是挺方便的,在ajax调用返回纯字符串时有中文编码问题. @ResponseBody @RequestMapping(value="/dec ...

  5. 深入理解计算机系统第二版习题解答CSAPP 2.20

    T2Uw(w)=x, x≥0时 T2Uw(w)=x+2w, x<0时 利用上面的公式,重新计算2.19的问题.

  6. Webservice简单概念

    一.序言 大家或多或少都听过 WebService(Web服务),有一段时间很多计算机期刊.书籍和网站都大肆的提及和宣传WebService技术,其中不乏很多吹嘘和做广告的成 分.但是不得不承认的是W ...

  7. [设计模式]<<设计模式之禅>>之关于单一职责原则

    单一职责原则的英文名称是Single Responsibility Principle,简称是SRP. 这个原则存在争议之处在哪里呢?就是对职责的定义,什么是类的职责,以及怎么划分类的职责.我们先举个 ...

  8. poj 1523 求割点

    思路:对于所有节点,每次找的子树,key[root]++;输出时,对于根节点就输出key[root],对于其它节点i,输出key[i]+1; #include<iostream> #inc ...

  9. mac 如何进入/usr/sbin目录

    1.进入terminal, 输入 ls /usr/sbin 2.在finder>前往文件夹,输入路径/usr/sbin

  10. MyBatis(3.2.3) - Configuring MyBatis using XML, typeAliases

    In the SQL Mapper configuration file, we need to give the fully qualified name of the JavaBeans for ...