《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);
}
}
}
《WPF程序设计指南》读书笔记——第4章 按钮与其他控件的更多相关文章
- 【WPF学习】第六十五章 创建无外观控件
用户控件的目标是提供增补控件模板的设计表面,提供一种定义控件的快速方法,代价是失去了将来的灵活性.如果喜欢用户控件的功能,但需要修改使其可视化外观,使用这种方法就有问题了.例如,设想希望使用相同的颜色 ...
- css权威指南读书笔记-第10章浮动和定位
这一章看了之后真是豁然开朗,之前虽然写了圣杯布局和双飞翼布局,有些地方也是模糊的,现在打算总结之后再写一遍. 以下都是从<css权威指南>中摘抄的我认为很有用的说明. 浮动元素 一个元素浮 ...
- 《Javascript高级程序设计》读书笔记(1-3章)
第一章 JavaScript简介 1.1 JavaScript简史 略 1.2 JavaScript实现 虽然 JavaScript 和 ECMAScript 通常都被人们用来表达相同的含义,但 Ja ...
- JavaScript权威指南读书笔记【第一章】
第一章 JavaScript概述 前端三大技能: HTML: 描述网页内容 CSS: 描述网页样式 JavaScript: 描述网页行为 特点:动态.弱类型.适合面向对象和函数式编程的风格 语法源自J ...
- 《JavaScript高级程序设计》 - 读书笔记 - 第5章 引用类型
5.1 Object 类型 对象是引用类型的实例.引用类型是一种数据结构,用于将数据和功能组织在一起. 新对象是使用new操作符后跟一个构造函数来创建的.构造函数本身就是一个函数,只不过该函数是出于创 ...
- 《JavaScript高级程序设计》 - 读书笔记 - 第4章 变量、作用域和内存问题
4.1 基本类型和引用类型的值 JavaScript变量是松散类型的,它只是保存特定值的一个名字而已. ECMAScript变量包含两种数据类型的值:基本类型值和引用类型值.基本类型值指的是简单的数据 ...
- 《Linux程序设计》--读书笔记---第十三章进程间通信:管道
管道:进程可以通过它交换更有用的数据. 我们通常是把一个进程的输出通过管道连接到另一个进程的输入: 对shell命令来说,命令的连接是通过管道字符来完成的: cmd1 | cmd2 sh ...
- 《Visual C++ 程序设计》读书笔记 ----第8章 指针和引用
1.&取地址:*取内容. 2.指针变量“++”“--”,并不是指针变量的值加1或减1,而是使指针变量指向下一个或者上一个元素. 3.指针运算符*与&的优先级相同,左结合:++,--,* ...
- 《Linux内核设计与实现》第八周读书笔记——第四章 进程调度
<Linux内核设计与实现>第八周读书笔记——第四章 进程调度 第4章 进程调度35 调度程序负责决定将哪个进程投入运行,何时运行以及运行多长时间,进程调度程序可看做在可运行态进程之间分配 ...
随机推荐
- 字体的大小(pt)和像素(px)如何转换?
px:相对长度单位.像素(Pixel). pt:绝对长度单位.点(Point). 1in = 2.54cm = 25.4 mm = 72pt = 6pc 具体换算是: Points Pixels Em ...
- iOS银行卡合法性校验
项目中用到了校验银行卡,就拿来贴上来了 + (BOOL)checkCardNo:(NSString*)cardNo;//判断银行卡 + (BOOL)checkCardNo:(NSString*)car ...
- linux的cron服务及应用
Linux下的Cron用于定时执行设置的周期性指令,是Linux的内置服务,可以用以下的方法启动.关闭这个服务: /sbin/service crond start //启动服务 /sbin/serv ...
- HTML的style属性
HTML的style属性 HTML的style属性提供了一种改变HTML样式的通用方法.style是在HTML4版本中引用的,它是一种首选的改变HTML元素样式的方法.可以使用style直接的将样式添 ...
- hdu 2412 树形DP
思路:对于最大的人数很容易想到,就直接dp.但对于最大值是否唯一就需要应用辅助数组,isOnly[i][0]表示dp[i][0]是否唯一,同理isOnly[i][1]. 那么当(dp[v][0]> ...
- VS中的波浪线
绿色波浪线: 如果你的代码中出现了绿色的波浪线,说明你的代码语法并没有错误, 只不过提示你有可能会出现错误,但是不一定会出现错误.警告线 红色波浪线: 如果你的代码中出现了红色的波浪线,意味着你的代码 ...
- css hack 大全 各个浏览器的css
各个浏览器的css hack区别属性: IE6: _zoom:1; IE6/7: *zoom:1; IE6/7/8/9 :\9 各个浏览器的css hack区别规则 IE6: *html{} IE7: ...
- html JS打印添加水印图片
最后,听取了别人的意见,换了个思路.将水印图和需要打印的内容放在一个div里面, 给打印的div设置较高的层级,这样水印自然就在最下面了.下面贴上部分代码: html: <div class=& ...
- JMS - ExceptionListener
If a JMS provider detects a problem with a connection, it will inform the connection’s ExceptionList ...
- Nginx - Additional Modules, About Your Visitors
The following set of modules provides extra functionality that will help you find out more informati ...