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. Java SE ---数据类型

    Java中数据类型(Data Type)分为基本数据类型(Primitive Data Type)和引用类型(Reference Data Type). Java中的基本数据类型共有以下8种:   1 ...

  2. CF Drazil and Date (奇偶剪枝)

    Drazil and Date time limit per test 1 second memory limit per test 256 megabytes input standard inpu ...

  3. [改善Java代码]构造代码块会想你所想

    建议37: 构造代码块会想你所想 镜像博文:http://www.cnblogs.com/DreamDrive/p/5413408.html http://www.cnblogs.com/DreamD ...

  4. 【解决】该任务映像已损坏或已篡改。(异常来自HRESULT:0x80041321)

    把系统升级到Windows 10,体验了一番Windows 10.感觉不怎么好用退回到了Windows 7,发现我原来自定义的任务计划没有按时执行,于是打开任务计划,弹出了下面的对话框[该任务映像已损 ...

  5. VS的启动方式

    启动VS的两种方式1.双击图标2.调出cmd,输入 devenv

  6. Jackson - Quickstart

    JSON Three Ways Jackson offers three alternative methods (one with two variants) for processing JSON ...

  7. Ehcache(2.9.x) - API Developer Guide, Using Explicit Locking

    About Explicit Locking Ehcache contains an implementation which provides for explicit locking, using ...

  8. HDOJ2007平方和与立方和

    平方和与立方和 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Sub ...

  9. linux中sed用法

    sed是一个很好的文件处理工具,本身是一个管道命令,主要是以行为单位进行处理,可以将数据行进行替换.删除.新增.选取等特定工作,下面先了解一下sed的用法sed命令行格式为:         sed ...

  10. mssql 查询效率

    (1)临时表.表变量 据说:当数据量<100行数据时使用表变量,数据量较大时使用临时表(可创建索引提高查询效率). 表变量只能创建主键或唯一索引,准确讲是约束不是索引. (2)存储过程直接在查询 ...