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. linux下 yum源、rpm、源代码安装mysql

    mysql的安装 一.yum源格式安装mysql 1.将下载的yum包上传到linux上: [root@localhost ~]# ls mysql-community-release-el6-5.n ...

  2. JPA与ORM以及Hibernate

  3. postgresql常用SQL

    --查看数据库 select * from pg_database; --查看表空间 select * from pg_tablespace; --查看语言 select * from pg_lang ...

  4. appendChild()插入节点需注意的问题

    第一点:首先appendChild插入节点时返回的值是插入的节点本身,另外必须要找到所要插入的父节点: var returnNode = parentNode.appendChild(childNod ...

  5. 设计模式——java

    设计模式:一个程序员对设计模式的理解:“不懂”为什么要把很简单的东西搞得那么复杂.后来随着软件开发经验的增加才开始明白我所看到的“复杂”恰恰就是设计模式的精髓所在,我所理解的“简单”就是一把钥匙开一把 ...

  6. 减小iOS应用程序的大小

    减小iOS应用程序的大小 本文译自:Reducing the size of my App Q: 怎样才能让我的程序安装包小一点,让程序的下载和安装更快速? A: 本文收集了一些减小程序安装包大小的相 ...

  7. HDOJ2021发工资咯:)

    发工资咯:) Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Subm ...

  8. ASP.NET实现折线图的绘制

    用到.Net中绘图类,实现折线图的绘制,生成图片,在页面的显示,代码如下: /// <summary> /// 获取数据 /// strChartName:图名称: /// yName:纵 ...

  9. dispatch_async & dispatch_sync

    Clear that! dispatch_async 是将block发送到指定线程去执行,当前线程不会等待,会继续向下执行. dispatch_sync 也是将block发送到指定的线程去执行,但是当 ...

  10. (转)使用CruiseControl+SVN+ANT实现持续集成之三

    在上一节中我们介绍了环境搭建和配置介绍,并快速启动CC查看集成结果,在本节中我们将详细介绍CC构建操作及监视. 1. 启动CC服务器 通过执行其根目录下的cruisecontrol.bat文件来启动C ...