WPF使用哪几种元素作为顶级元素:

1. Window元素

2. Page元素(与Window元素类似,用于可导航的应用程序)

3. Application元素(定义应用程序资源和启动设置)

PS:在一个WPF应用程序中只能有一个顶级元素

 <Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid> </Grid>
</Window>

Class是类

xmlns是XML Namespaces的缩写,中文名称是XML(标准通用标记语言的子集)命名空间

Xmlns[:可选的映射前缀]=“名称空间”

为元素命名:(以Grid元素为例)

例一:

 <Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Name="grid1"> </Grid>
</Window>

例二:

 <Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Name>grid1</Grid.Name>
</Grid>
</Window>

以上两个例子等效

以上是UI层面的代码

逻辑代码层面调用上面的Grid元素的Name属性为例:

下面代码执行后会把窗体的标题改为Grid元素的名字属性(试了<Grid.Name>grid1</Grid.Name>无效)

UI层代码

 <Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid Name="grid1">
</Grid>
</Window>

逻辑层代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace WpfApplication2
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
} private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Title = this.grid1.Name;
}
}
}

简单元素例子:

新建一个button按钮和textbox文本框,实现功能:点击button按钮弹出对话框打印textbox文本框的内容

UI层:

 <Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid Name="grid1">
<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="91,130,0,0" Click="Button_Click_1"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="91,61,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" Name="txtShow"/>
</Grid>
</Window>

逻辑层:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace WpfApplication2
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
} private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Title = this.grid1.Name;
} private void Button_Click_1(object sender, RoutedEventArgs e)
{
MessageBox.Show(txtShow.Text);
}
}
}

背景颜色渐变例子:

UI层:(只需修改UI层,逻辑层不变)

 <Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid Name="grid1">
<Grid.Background>
<LinearGradientBrush>
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0.00" Color="Red"/>
<GradientStop Offset="0.50" Color="Green"/>
<GradientStop Offset="1.00" Color="Blue"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Grid.Background>
<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="91,130,0,0" Click="Button_Click_1"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="91,61,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" Name="txtShow"/>
</Grid>
</Window>

运行效果:

用代码来创建WPF窗体:

新建个WPF的项目,把项目中的XAML文件都排除了,然后添加两个类,如图:

Class1类代码如下:

 using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup; namespace WPF基础
{
class Class1:Window
{
private Button button1;
public Class1()
{
InitializeComponent();
}
private void InitializeComponent()
{
//设置窗体
this.Width = ;
this.Height = ;
this.Left = this.Top = ;
this.Title = "代码创建的新窗体";
//创建停靠面板对象
DockPanel panel = new DockPanel();
//创建按钮对象
button1 = new Button();
button1.Content = "请点击";
button1.Margin = new Thickness();
button1.Click += button1_Click;//注册按钮事件 IAddChild container = panel;//不明白IAddChild作用是什么
container.AddChild(button1);//添加子对象 container = this;
container.AddChild(panel);
}
private void button1_Click(object sender,RoutedEventArgs e)
{
button1.Content = "已点击";
}
}
}

Class2代码如下:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows; namespace WPF基础
{
class Class2:Application
{
[STAThread()]//单线程的东西,不明白(指示应用程序的 COM 线程模型是单线程单元 (STA)。)
static void Main()
{
Class2 app = new Class2();
app.MainWindow = new Class1();
app.MainWindow.ShowDialog();//模态化打开窗体
}
}
}

设置项目属性:(启动对象设置为Class2类)

使用代码和未经编译的标记XAML创建WPF应用程序:

新建一个文本,输入以下代码,并把文本文件改为xaml后缀格式的xaml文件:(文件名:Window2.xaml)

 <DockPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Button Name="button1" Margin="">Please click me.</Button>
</DockPanel>

以上新建的文件放入将会新建的WPF程序的根目录:

一般在文件夹下

新建WPF窗体(窗体名:Window2)

窗体逻辑层代码如下:

 using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.Windows.Markup; namespace WPF基础
{
/// <summary>
/// Window1.xaml 的交互逻辑
/// </summary>
public partial class Window1 : Window
{
private Button myButton;
public Window1()
{
InitializeComponent();
}
public Window1(string xmalFile)
{
//设置窗体
this.Width = this.Height = ;
this.Left = this.Top = ;
this.Title = "动态加载XAML文档"; //从外部的XAML文件里获取XAML内容
DependencyObject ddo;
using (FileStream fs = new FileStream(xmalFile, FileMode.Open))
{
ddo = (DependencyObject)XamlReader.Load(fs);
}
this.Content = ddo;
myButton = (Button)LogicalTreeHelper.FindLogicalNode(ddo, "button1");
myButton.Click += myButton_Click;
}
private void myButton_Click(object sender, RoutedEventArgs e)
{
myButton.Content = "已点击";
}
}
}

修改上一个例子的启动类(Class2),代码如下:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows; namespace WPF基础
{
class Class2:Application
{
[STAThread()]//单线程的东西,不明白(指示应用程序的 COM 线程模型是单线程单元 (STA)。)
static void Main()
{
//设置启动Class1类的代码构建WPF窗体
//Class2 app = new Class2();
//app.MainWindow = new Class1();
//app.MainWindow.ShowDialog();//模态化打开窗体 //设置启动WPF窗体Window1
Class2 app = new Class2();
app.MainWindow = new Window1("Window2.xaml");
app.MainWindow.ShowDialog();
}
}
}

运行效果:

附上源代码文件:

WPF基础.rar

使用StackPanel面板进行简单布局:

UI层代码:

 <Window x:Class="StackPanel面板.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Border Background="red" BorderThickness="20" Padding="25" CornerRadius="30">
<!-- Background="red" 背景颜色=“红色” BorderThickness="20" 边框粗细=“20像素” Padding="25" 容器边缘到内部控件的距离=“25像素” 也可以Padding="10,0,5,0"这样填 CornerRadius="30" 设置边框圆角-->
<StackPanel Name="stackPanel1" Orientation="Vertical">
<!-- Orientation="Horizontal" 方向属性=水平方向,Vertical垂直方向-->
<Label Content="Label"/>
<Button Content="Button1" HorizontalAlignment="Left"/>
<!-- HorizontalAlignment="Left" 水平方向=左-->
<Button Content="Button2" VerticalAlignment="Center"/>
<!-- VerticalAlignment="Center" 垂直方向=居中-->
<Button Content="Button3" Margin="0,0,10,0" MinWidth="20" MaxWidth="200"/>
<!-- Margin="0,0,10,0" 边距=“左,顶,右,底”MinWidth="20" 最小宽度=“20像素” MaxWidth="200" 最大宽度=“200像素”-->
<Button Content="Button4"/>
</StackPanel>
</Border>
</Window>

运行效果:

WrapPanel面板设置:

WrapPanel布局面板将各个控件从左至右按照行或列的顺序罗列,当长度或高度不够是就会自动调整进行换行,后续排序按照从上至下或从右至左的顺序进行。

Orientation——根据内容自动换行。当 Horizontal选项看上去类似于Windows资源管理器的缩略图视图:元素是从左向右排列的,然后自上至下自动换行。Vertical 选项看上去类似于Windows资源管理器的列表视图:元素是从上向下排列的,然后从左至右自动换行。

ItemHeight——所有子元素都一致的高度。每个子元素填充高度的方式取决于它的VerticalAlignment属性、Height属性等。任何比ItemHeight高的元素都将被截断。

ItemWidth——所有子元素都一致的宽度。每个子元素填充高度的方式取决于它的VerticalAlignment属性、Width属性等。任何比ItemWidth高的元素都将被截断。

DockPanel面板设置:

UI层代码:

 <Window x:Class="StackPanel面板.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Border Background="red" BorderThickness="20" Padding="25" CornerRadius="30">
<!-- Background="red" 背景颜色=“红色” BorderThickness="20" 边框粗细=“20像素” Padding="25" 容器边缘到内部控件的距离=“25像素” 也可以Padding="10,0,5,0"这样填 CornerRadius="30" 设置边框圆角-->
<DockPanel >
<Button Content="left" DockPanel.Dock="Left"/>
<Button Content="top" DockPanel.Dock="Top"/>
<Button Content="bottom" DockPanel.Dock="Bottom"/>
<Button Content="right" DockPanel.Dock="Right"/>
<Button Content="Btn4" Height="25"/>
<Button Content="Btn5" Width="50"/>
</DockPanel>
</Border>
</Window>

运行效果:

如果DockPanel设置了LastChildFill属性为True就是把最后一个控件元素填充剩下的空间(<DockPanel LastChildFill="True">)

UI层代码:

 <Window x:Class="StackPanel面板.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Border Background="red" BorderThickness="20" Padding="25" CornerRadius="30">
<!-- Background="red" 背景颜色=“红色” BorderThickness="20" 边框粗细=“20像素” Padding="25" 容器边缘到内部控件的距离=“25像素” 也可以Padding="10,0,5,0"这样填 CornerRadius="30" 设置边框圆角-->
<DockPanel LastChildFill="True">
<Button Content="left" DockPanel.Dock="Left"/>
<Button Content="top" DockPanel.Dock="Top"/>
<Button Content="bottom" DockPanel.Dock="Bottom"/>
<Button Content="right" DockPanel.Dock="Right"/>
<Button Content="Btn4" Height="25"/>
<Button Content="Btn5" />
</DockPanel>
</Border>
</Window>

运行效果:

利用以上知识嵌套:

UI层代码:

 <Window x:Class="StackPanel面板.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" HorizontalAlignment="Right">
<!-- DockPanel.Dock="Bottom" 设置在DockPanel面板中的位置 Orientation="Horizontal" 方向属性=水平方向 HorizontalAlignment="Right" 水平方向=右-->
<Button Content="OK" Margin="10,10,2,10" Padding="3"/>
<Button Content="Cancel" Margin="2,10,10,10" Padding="3"/>
</StackPanel>
<TextBox DockPanel.Dock="Bottom">这是一个文本框</TextBox>
</DockPanel>
</Window>

运行效果:

Grid面板使用:

UI层代码:

 <Window x:Class="StackPanel面板.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid ShowGridLines="False" UseLayoutRounding="True">
<!-- ShowGridLines="False" 显示网格=“否”, UseLayoutRounding="True" 边缘清晰=“是”-->
<Grid.RowDefinitions>
<!-- Grid.RowDefinitions 设置行-->
<RowDefinition></RowDefinition>
<!-- RowDefinition 新增一行-->
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<!-- Grid.ColumnDefinitions 设置列-->
<ColumnDefinition Width="*" MinWidth="50"></ColumnDefinition>
<!-- ColumnDefinitio 新增一列 Width="*" 设定宽度标准*,以后出现的*就是相等标准,2*就是两倍标准,以此类推,MinWidth="50" 最小宽度=“50像素”-->
<ColumnDefinition Width="Auto"></ColumnDefinition>
<!-- Width="Auto" 宽度=“自动”-->
<ColumnDefinition Width="2*" MinWidth="50"></ColumnDefinition>
<ColumnDefinition Width="4*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button Content="LeftTop" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" Margin="3"/>
<!-- Grid.Row="0" 所在行=“0”,Grid.Column="0" 所在列=“0”,Grid.ColumnSpan="2" 占用列空间=“2”, Margin="3" 控件边缘到字体的长度=“3”-->
<Button Content="CenterTop" Grid.Row="0" Grid.Column="2" Margin="3"/>
<Button Content="RightBottom" Grid.Row="1" Grid.Column="2" Grid.ColumnSpan="2" Margin="3"/>
<GridSplitter Grid.Column="1" Width="3" Grid.RowSpan="2" VerticalAlignment="Stretch" HorizontalAlignment="Center"/>
<!-- GridSplitter控件可拖动改变该控件左右两边的列的大小,VerticalAlignment="Stretch" 垂直方向设置=“从顶到底”,HorizontalAlignment="Center" 水平方向设置=“居中”-->
</Grid>
</Window>

运行效果:

关于Grid面板的共享尺寸组属性(SharedSizeGroup):

设置列ColumnDefinition 属性中的 SharedSizeGroup ,SharedSizeGroup的值相同时,可以控制一个Grid中的列和另外一个Gird中的某一列的宽度相同。
还有一个要注意的是 顶级Grid元素的IsSharedSizeScope要设置为True

UI代码:

 <Window x:Class="StackPanel面板.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Grid.IsSharedSizeScope="True" Margin="3" ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Margin="3" Background="LightYellow" ShowGridLines="True">
<Grid.ColumnDefinitions >
<ColumnDefinition Width="Auto" SharedSizeGroup="TextLabel"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Margin="5">A very long bit of text</Label>
<!-- 如果是第一行或者第一列,这个属性可以不声明,默认就是-->
<Label Grid.Column="1" Margin="5">More text</Label>
<TextBox Grid.Column="2" Margin="5">A text box</TextBox>
</Grid>
<Label Grid.Row="1">Some text in between the two grids</Label>
<Grid Grid.Row="2" Margin="3" Background="LightBlue" ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="TextLabel"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Margin="5">Short</Label>
<TextBox Grid.Column="1" Margin="5">A text box</TextBox>
</Grid>
</Grid>
</Window>

运行效果:

Canvas面板使用:

使用绝对定位,如果窗口的大小小于canvas面板,一部分内容会看不见,canvas中的项不能自动调整大小,在canvas内的控件指定左上角,用Canvas.Top和Canvas.Left属性。

例子:

UI层代码(含有Z层顺序):

 <Window x:Class="StackPanel面板.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Canvas>
<Button Name="btn1" Content="Button1" Canvas.Left="173" Canvas.Top="108" Width="75" Click="btn1_Click"/>
<!-- Canvas.Left="173" Canvas.Top="108" 这个两个分别表示从左边(顶部)到控件的距离,而且对立方向只能设置一个,即你设置了左边就不能设置右边-->
<Button Name="btn2" Content="Button2" Canvas.ZIndex="1" Canvas.Right="270" Canvas.Top="185" Width="75" Canvas.Left="294"/>
<!-- Canvas.ZIndex="1" 表示显示的顺序层,数字越大离我们越近,所有控件默认设置都为0-->
<DataGrid Canvas.Left="262" Canvas.ZIndex="10" Canvas.Top="168" Height="62" Width="127"/>
</Canvas>
</Window>

逻辑层代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace StackPanel面板
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
//设置btn2按钮控件的层顺序为20
Canvas.SetZIndex(this.btn2,);
}
}
}

运行效果:(按下Button1按钮前)

(按下Button2按钮后)

InkCanvas面板使用:

UI层代码:

 <Window x:Class="StackPanel面板.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<ComboBox Name="EditingMode" Margin="5" SelectionChanged="EditingMode_SelectionChanged" />
<!-- SelectionChanged="EditingMode_SelectionChanged" 假如ComboBox发生改变,触发EditingMode_SelectionChanged事件-->
</StackPanel>
<InkCanvas Name="InkC" Grid.Row="1" EditingMode="select">
<Button InkCanvas.Left="50" InkCanvas.Top="180" Content="Button1"/>
</InkCanvas>
</Grid>
</Window>

逻辑层代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace StackPanel面板
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//历遍InkCanvasEditingMode类型
foreach(InkCanvasEditingMode mode in Enum.GetValues(typeof(InkCanvasEditingMode)))
{
//把InkCanvasEditingMode类型逐个加入ComboBox下拉多选框(EditingMode)中
this.EditingMode.Items.Add(mode);
}
//ComboBox下拉多选框默认选项
this.EditingMode.SelectedIndex = ;
}
//如果ComboBox下拉多选框发生改变
private void EditingMode_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//改变InkCanvas面板(InkC)属性为ComboBox下拉多选框中所选选项
this.InkC.EditingMode = (InkCanvasEditingMode)this.EditingMode.SelectedItem;
}
}
}

运行效果:

随便测试下功能:

INK(画笔)功能:

Select功能:

补充一点:

Image的Stretch属性:

有时候我们在WPF程序中设置了图片的Width和Height,但图片显示出来的宽和高并不是我们预期的效果,这实际上是由于Image的默认Stretch属性导致的

Image的Stretch属性默认为Uniform,这代表图片会均匀的变大和缩小,保证了图片的比例不失调,而往往我们设置的宽和高并不符合图片的比例,因此显示效果就

不是我们预期所想,Image的Stretch属性还可以设置为以下值:

None —— 图片会按原始大小显示

Fill —— 图片会按照设置的Width和Height显示,比例会失调

UniformToFill —— 图片会按照设置的Width和Height显示,但图片是均匀变大和缩小的,比例不失调,超出显示范围的图像会被截掉

路由事件:

分三种:

1.直接路由事件

2.冒泡路由事件

3.隧道路由事件

冒泡路由事件例子:

UI层代码:

 <Window x:Class="WPF路由事件.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
MouseUp="SomethingClicked">
<!-- MouseUp="SomethingClicked"设置顶级的路由事件-->
<Grid Margin="3" MouseUp="SomethingClicked">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Margin="5" Background="AliceBlue" BorderBrush="Black" BorderThickness="3" MouseUp="SomethingClicked"
HorizontalAlignment="Left">
<!-- Background="AliceBlue" 背景色="AliceBlue", BorderBrush="Black" 笔刷颜色=“黑色”,BorderThickness="3" 边框宽度=“3”,MouseUp="SomethingClicked"设置本级的路由事件-->
<StackPanel MouseUp="SomethingClicked">
<TextBlock Margin="3" MouseUp="SomethingClicked">
Image and picture label
</TextBlock>
<Image Height="50" Width="50"
Source="D:\我的文档\Visual Studio 2012\Projects\WPF路由事件\WPF路由事件\Image\play_button.png"
Stretch="Uniform" MouseUp="SomethingClicked" />
<!-- Stretch="Uniform" 设置延伸属性,这里表示图片会均匀的变大和缩小,保证了图片的比例不失调,详细看上面补充-->
<TextBlock Margin="3" MouseUp="SomethingClicked">
Courtesy of the StackPanel
</TextBlock>
</StackPanel>
</Label>
<ListBox Margin="5" Name="lstMessages" Grid.Row="1"></ListBox>
<CheckBox Margin="5" Grid.Row="2" Name="chkHandle">Handle first event</CheckBox>
<Button Click="cmdClear_Click" Grid.Row="3" HorizontalAlignment="Right" Margin="5" Padding="3">
Clear List
</Button>
</Grid>
</Window>

逻辑层代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace WPF路由事件
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
protected int eventCounter = ;
private void SomethingClicked(object sender,RoutedEventArgs e)
{
//object sender 触发事件的对象,RoutedEventArgs e 路由事件(含相关属性)
eventCounter++;
//sender.ToString() 触发事件的字符化
//e.Source 指示引发事件的对象,e.OriginalSource是更深层次的指示引发事件的对象,一般OriginalSource与Source一样
string message = "#" + eventCounter.ToString() + ":\r\n" +
"Sender:" + sender.ToString() + "\r\n" +
"Source:" + e.Source + "\r\n" +
"Original Source:" + e.OriginalSource;
//ListBox控件lstMessages
lstMessages.Items.Add(message);
//Handled事件:挂起(即终止,这里是指终止路由事件的传递)
e.Handled = (bool)chkHandle.IsChecked;
}
private void cmdClear_Click(object sender, RoutedEventArgs e)
{
eventCounter = ;
lstMessages.Items.Clear();
}
}
}

文档大纲:

运行效果(点击前):

(点击后):

隧道路由事件:

修改上面的例子的MouseUp事件为PreviewMouseUp事件即可为隧道路由事件(Preview为隧道路由的标签)

UI层代码:

 <Window x:Class="WPF路由事件.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
PreviewMouseUp="SomethingClicked">
<!-- PreviewMouseUp="SomethingClicked" 设置顶级的路由事件,加了Preview就是隧道路由事件-->
<Grid Margin="3" PreviewMouseUp="SomethingClicked">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Margin="5" Background="AliceBlue" BorderBrush="Black" BorderThickness="3" PreviewMouseUp="SomethingClicked"
HorizontalAlignment="Left">
<!-- Background="AliceBlue" 背景色="AliceBlue", BorderBrush="Black" 笔刷颜色=“黑色”,BorderThickness="3" 边框宽度=“3”,PreviewMouseUp="SomethingClicked" 设置本级的路由事件,加了Preview就是隧道路由事件-->
<StackPanel PreviewMouseUp="SomethingClicked">
<TextBlock Margin="3" PreviewMouseUp="SomethingClicked">
Image and picture label
</TextBlock>
<Image Height="50" Width="50"
Source="D:\我的文档\Visual Studio 2012\Projects\WPF路由事件\WPF路由事件\Image\play_button.png"
Stretch="Uniform" PreviewMouseUp="SomethingClicked" />
<!-- Stretch="Uniform" 设置延伸属性,这里表示图片会均匀的变大和缩小,保证了图片的比例不失调,详细看上面补充-->
<TextBlock Margin="3" PreviewMouseUp="SomethingClicked">
Courtesy of the StackPanel
</TextBlock>
</StackPanel>
</Label>
<ListBox Margin="5" Name="lstMessages" Grid.Row="1"></ListBox>
<CheckBox Margin="5" Grid.Row="2" Name="chkHandle">Handle first event</CheckBox>
<Button Click="cmdClear_Click" Grid.Row="3" HorizontalAlignment="Right" Margin="5" Padding="3">
Clear List
</Button>
</Grid>
</Window>

逻辑层代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace WPF路由事件
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
protected int eventCounter = ;
private void SomethingClicked(object sender,RoutedEventArgs e)
{
//object sender 触发事件的对象,RoutedEventArgs e 路由事件(含相关属性)
eventCounter++;
//sender.ToString() 触发事件的字符化
//e.Source 指示引发事件的对象,e.OriginalSource是更深层次的指示引发事件的对象,一般OriginalSource与Source一样
string message = "#" + eventCounter.ToString() + ":\r\n" +
"Sender:" + sender.ToString() + "\r\n" +
"Source:" + e.Source + "\r\n" +
"Original Source:" + e.OriginalSource;
//ListBox控件lstMessages
lstMessages.Items.Add(message);
//Handled事件:挂起(即终止,这里是指终止路由事件的传递)
e.Handled = (bool)chkHandle.IsChecked;
}
private void cmdClear_Click(object sender, RoutedEventArgs e)
{
eventCounter = ;
lstMessages.Items.Clear();
}
}
}

文档大纲:

运行效果(点击前):

(点击后)

另一个隧道路由例子:

UI层代码:

 <Window x:Class="WPF路由事件.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
PreviewKeyDown="SomeKeyPressed">
<Grid Margin="3" PreviewKeyDown="SomeKeyPressed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Label Margin="5" Background="AliceBlue" BorderBrush="Black" BorderThickness="1"
HorizontalContentAlignment="Stretch" PreviewKeyDown="SomeKeyPressed">
<StackPanel PreviewKeyDown="SomeKeyPressed">
<TextBox Margin="3" HorizontalAlignment="Center" PreviewKeyDown="SomeKeyPressed">
Image and text label
</TextBox>
<Image Source="D:\我的文档\Visual Studio 2012\Projects\WPF路由事件\WPF路由事件\Image\play_button.png"
PreviewKeyDown="SomeKeyPressed" Width="50" Height="50"/>
<DockPanel Margin="0,5,0,0" PreviewKeyDown="SomeKeyPressed">
<TextBlock Margin="3" PreviewKeyDown="SomeKeyPressed">
Type here:
</TextBlock>
<TextBox PreviewKeyDown="SomeKeyPressed" KeyDown="SomeKeyPressed"></TextBox>
</DockPanel>
</StackPanel>
</Label>
<ListBox Name="lstMessages" Grid.Row="1" Margin="5"/>
<CheckBox Margin="5" Grid.Row="2" Name="chkHandle">Handle first event</CheckBox>
<Button Click="cmdClear_Click" Grid.Row="3" HorizontalAlignment="Right" Margin="5" Padding="3">
Clear List</Button>
</Grid>
</Window>

逻辑层代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace WPF路由事件
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
protected int eventCounter = ;
private void SomeKeyPressed(object sender, RoutedEventArgs e)
{
eventCounter++;
string message = "#" + eventCounter.ToString() + ":\r\n" +
"Sender:" + sender.ToString() + "\r\n" +
"Source:" + e.Source + "\r\n" +
"Original Source:" + e.OriginalSource + "\r\n" +
"Event:" + e.RoutedEvent;
lstMessages.Items.Add(message);
e.Handled = (bool)chkHandle.IsChecked; }
private void cmdClear_Click(object sender, RoutedEventArgs e)
{
eventCounter = ;
lstMessages.Items.Clear();
}
}
}

文档大纲:

运行效果(键盘点击前):

(键盘点击后):

WPF自学笔记的更多相关文章

  1. 《Linux内核设计与实现》课本第四章自学笔记——20135203齐岳

    <Linux内核设计与实现>课本第四章自学笔记 进程调度 By20135203齐岳 4.1 多任务 多任务操作系统就是能同时并发的交互执行多个进程的操作系统.多任务操作系统使多个进程处于堵 ...

  2. 《Linux内核设计与实现》课本第三章自学笔记——20135203齐岳

    <Linux内核设计与实现>课本第三章自学笔记 进程管理 By20135203齐岳 进程 进程:处于执行期的程序.包括代码段和打开的文件.挂起的信号.内核内部数据.处理器状态一个或多个具有 ...

  3. 《Linux内核设计与实现》课本第十八章自学笔记——20135203齐岳

    <Linux内核设计与实现>课本第十八章自学笔记 By20135203齐岳 通过打印来调试 printk()是内核提供的格式化打印函数,除了和C库提供的printf()函数功能相同外还有一 ...

  4. python自学笔记

    python自学笔记 python自学笔记 1.输出 2.输入 3.零碎 4.数据结构 4.1 list 类比于java中的数组 4.2 tuple 元祖 5.条件判断和循环 5.1 条件判断 5.2 ...

  5. ssh自学笔记

    Ssh自学笔记 Ssh简介 传统的网络服务程序,如:ftp.pop和telnet在本质上都是不安全的,因为它们在网络上用明文传送口令和数据,别有用心的人非常容易就可以截获这些口令和数据.而且,这些服务 ...

  6. 《深入浅出WPF》笔记——绘画与动画

    <深入浅出WPF>笔记——绘画与动画   本篇将记录一下如何在WPF中绘画和设计动画,这方面一直都不是VS的强项,然而它有一套利器Blend:这方面也不是我的优势,幸好我有博客园,能记录一 ...

  7. JavaScript高级程序设计之自学笔记(一)————Array类型

    以下为自学笔记. 一.Array类型 创建数组的基本方式有两种: 1.1第一种是使用Array构造函数(可省略new操作符). 1.2第二种是使用数组字面量表示法. 二.数组的访问 2.1访问方法 在 ...

  8. WPF自学入门(三)WPF路由事件之内置路由事件

    有没有想过在.NET中已经有了事件机制,为什么在WPF中不直接使用.NET事件要加入路由事件来取代事件呢?最直观的原因就是典型的WPF应用程序使用很多元素关联和组合起来,是否还记得在WPF自学入门(一 ...

  9. WPF自学入门(六)WPF带标题的内容控件简单介绍

    在WPF自学入门(二)WPF-XAML布局控件的文章中分别介绍StackPanel,WarpPanel,DockPanel,Grid,Canvas五种布局容器的使用,可以让我们大致了解容器可以使用在什 ...

随机推荐

  1. The basic introduction to MIX language and machine

    reference: The MIX Computer, The MIX Introduction sets, The basic info storage unit in MIX computer ...

  2. scanf一次给多个变量赋值

    本节课程笔记: 一是对多个变量进行赋值,二是对非法输入的值做正确处理(处理方式了解即可,相关函数知识后期讲解),三是美化scanf代码加入输出说明. /* Name:scanf一次给多个变量赋值 Co ...

  3. VS2010/MFC对话框:文件对话框

    文件对话框 上一讲介绍的是消息对话框,本节讲解文件对话框.文件对话框也是很常用的一类对话框. 文件对话框的分类       文件对话框分为打开文件对话框和保存文件对话框,相信大家在Windows系统中 ...

  4. les nationalités et les pays

    masculin  féminin pays français  française  la France chinois  chinoise  la Chine   suisse  suisse  ...

  5. bind和live

    <div> <ul> <li></li> <li></li> <li></li> <li>& ...

  6. .NET中的IO操作之文件流(一)

    读操作 //1.创建文件流 FileStream fsRead =new FileStream("1.txt",FileMode.Open); //2.创建缓冲区,正常情况下,是不 ...

  7. Android Developers:按需求加载视图

    有时候你的布局可能需要较少使用的复杂视图.无论它们是项目详情,进度指示器,或者处理的信息,你能通过在它们被需要的时候加载的方式,来减少内存消耗和加快显示. 定义一个ViewStub ————————— ...

  8. jquery ajax 使用

    异步刷新实现方式有多种,也可以借助JS的多种框架,下面是使用JQuery框架实现的AJAX 验证用户名是否存在 jQuery.ajax概述 HTTP 请求加载远程数据. 通过jQuery 底层 AJA ...

  9. ASP.NET MVC 中的 T4

    每次使用“添加视图”或“添加控制器”功能时,您都在 ASP.NET MVC 项目中使用 T4 模板.这些模板位于 Common7\IDE\ItemTemplates\CSharp\Web\MVC 2\ ...

  10. php学习笔记(3)

    1.计数器 <?php /* simple access counter for php3 (c)1998 David W. Bettis dbettis@eyeintegrated.com m ...