視頻二:XAML基礎
1.頂級元素 <Window></Window>,<Page></Page>,<Application></Application>
2. 名稱空間 很重要。 默認名稱空間:xmlns="" ; 另外名稱空間: xmlns:x="" ; x是名稱空間前綴
x:Class="WpfApplication1.MainWindow" 是繼續自Window類。
3. 簡單屬性:
實例1:簡單屬性
<Grid Name="Grid1"></Grid>
this.Title=this.Grid1.Name;
實例2:復雜屬性,屬性元素的方法
<Grid >
<Grid.Name>Grid1</Grid.Name>
<Button></Button>
</Grid>
4. 漸變的顏色
<Grid Name="Grid1">
<Grid.Background>
<LinearGradientBrush>
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0.00" Color="Red"/>
<GradientStop Offset="0.50" Color="Indigo"/>
<GradientStop Offset="1.00" Color="Violet"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Grid.Background>
</Grid>
5. 附加的屬性
<Button Content="Button1" HorizontalAlignment="Left" Margin="215,60,0,0" VerticalAlignment="Top" Width="75"/>
<Button Content="Button2" Grid.Row="1" HorizontalAlignment="Left" Margin="215,38,0,0" VerticalAlignment="Top" Width="75"/>
<Button Content="Button3" Grid.Row="2" HorizontalAlignment="Left" Margin="215,47,0,0" VerticalAlignment="Top" Width="75" />
其中:Grid.Row 默認從0開始,默認不寫, 這是一個附加屬性。
6.特殊字符
特殊字符串‘<’使用 ‘<’代替 ,特殊字符串‘>’使用 ‘>’代替
空格字符:xml:space="preserve" 添加屬性,可以完整顯示空格。
<TextBox HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="465" xml:space="preserve">where this is " "...</TextBox>
7. XAML事件
<Button Content="Button1" HorizontalAlignment="Left" Margin="215,60,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
按鈕的單擊事件
視頻三:只使用代碼創建WPF應用程序(缺點,慢;優點,自由。)
補充知識點:使用partial關鍵字的類是可以互相補充的類。 關鍵WPF有三種方式:a.僅使用代碼創建;b.僅使用頁面創建;c.兩者結合,相互補充。

using System.Windows; using System.Windows.Controls; using System.Windows.Markup; namespace _2014_10_09_WPF { class Window1:Window { private Button button1; public Window1() { InitializeComponent(); } private void InitializeComponent() { //設置窗體 this.Width = 285; this.Height = 250; this.Left = this.Top = 100; this.Title = "Code_Only Window"; //創建停靠面板對象 DockPanel panel = new DockPanel(); //創建按鈕對象 button1 = new Button(); button1.Content = "Please click me."; button1.Margin = new Thickness(30); //事件 button1.Click+=button1_Click; ////添加控件 IAddChild container = panel; container.AddChild(button1); container = this; container.AddChild(panel); } private void button1_Click(object sender,RoutedEventArgs e) { button1.Content = "Thank you."; } } }

using System; using System.Collections.Generic; using System.Text; using System.Windows; namespace _2014_10_09_WPF { class Program:Application { [STAThread] static void Main() { Program app = new Program(); app.MainWindow = new Window1(); app.MainWindow.ShowDialog(); } } }
視頻四:使用代碼和未經編譯的外部標記XAML文件,創建WPF應用程序
代碼如下:

////文件名稱:MainWindow.xaml.cs using System.Windows; using System.Windows.Controls; using System.IO; using System.Windows.Markup; namespace _2014_10_10使用代碼和未經編譯的標記XAML創建WPF應用程序 { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { private Button myButton; public MainWindow() { InitializeComponent(); } public MainWindow(string xamlFile) { //設置窗體 this.Width = this.Height = 285; this.Left = this.Top = 100; this.Title = "Dynamically loaded XAML"; //從外部的一個XAML文件里面獲取XAML內容 DependencyObject rootElement; using (FileStream fs = new FileStream(xamlFile, FileMode.Open)) { rootElement = (DependencyObject)XamlReader.Load(fs); } this.Content = rootElement; myButton =(Button)LogicalTreeHelper.FindLogicalNode(rootElement,"button1"); myButton.Click += myButton_Click; } private void myButton_Click(object sender,RoutedEventArgs e) { myButton.Content = "thank you."; } } }

////文件名稱:Program.cs using System; using System.Collections.Generic; using System.Text; using System.Windows; namespace _2014_10_10使用代碼和未經編譯的標記XAML創建WPF應用程序 { class Program:Application { [STAThread()] static void Main() { Program app = new Program(); app.MainWindow = new MainWindow("MainWindow.xaml"); app.MainWindow.ShowDialog(); } } }
視頻五:使用StackPanel面板進行簡單的布局(WPF布局原則,使用StackPanel布局,Border控件:邊距,邊緣,邊的大小) 堆棧面板,默認情況下是列排序方式。(垂直方向)
布局控件的使用:實例代碼

<Window x:Class="_2014_10_10使用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="706.7"> <Border BorderBrush="Black" BorderThickness="3" Margin="44.5,0,224.5,0" Padding="10" CornerRadius="10"> <StackPanel Name="stackPanel1" Orientation="Horizontal" HorizontalAlignment="Center"> <Label Content="Label" /> <Button Content="Button1" Margin="10,0,10,0" MinWidth="20" MaxWidth="200" /> <Button Content="Button2" /> <Button Content="Button3" /> <Button Content="Button4" /> </StackPanel> </Border> </Window>
視頻六:使用WrapPanel 面板和DockPanel 面板使用 (嵌套布局容器)
WrapPanel 默認情況是水平排序,行排序。wrap:包裹。 wrap up 偽裝。
DockPanel 一些使用方法,代碼如下:

<Window x:Class="使用WrapPanel_面板和DockPanel_面板使用__嵌套布局容器_.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 LastChildFill="True"> <Button Content="Top Button" DockPanel.Dock="Top" /> <Button Content="Bottom Button" DockPanel.Dock="Bottom"/> <Button Content="Left Button" DockPanel.Dock="Left" Width="75"/> <Button Content="Right Button" DockPanel.Dock="Right" Width="75"/> <Button Content="Remaining Button" /> </DockPanel> </Window>
嵌套布局容器實例:

<Window x:Class="使用WrapPanel_面板和DockPanel_面板使用__嵌套布局容器_.BasicDialogBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="BasicDialogBox" Height="300" Width="300"> <DockPanel Name="dockPanel1"> <StackPanel Name="stackPanel" DockPanel.Dock="Bottom" 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> <TextBlock Name="txtBox1" DockPanel.Dock="Top">This is a test.</TextBlock> </DockPanel> </Window>
視頻七: Grid面板 (調整行與列,布局舍入,跨越行與列,分割窗口,共享尺寸組)
調整行與列:Grid.Row="0" Grid.Column="1" 調整列的寬度:a. Width="200" b. Width="auto" c. Width="*" Width="2*" (a最不可取)
布局舍入: UseLayoutRounding="True" 解決圖片模糊問題
跨越行與列: Grid.RowSpan="2",Grid.ColumnSpan="2"
分割窗口:分割器對象: <GridSplitter Grid.Column="1" Grid.RowSpan="2" Width="3" VerticalAlignment="Stretch" HorizontalAlignment="Center" />
共享尺寸組:SharedSizeGroup="TextLable" 需要同名

<Window x:Class="_2014_10_10Grid面板.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="True" UseLayoutRounding="True" > <Grid.RowDefinitions> <RowDefinition ></RowDefinition> <RowDefinition ></RowDefinition> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" MinWidth="50"></ColumnDefinition> <ColumnDefinition Width="auto"></ColumnDefinition> <ColumnDefinition Width="2*" MinWidth="50"></ColumnDefinition> <ColumnDefinition Width="4*"></ColumnDefinition> </Grid.ColumnDefinitions> <Button Content="Left Top" Grid.Row="0" Grid.RowSpan="2" Grid.Column="0" Margin='3'/> <Button Content="Center Top" Grid.Row="0" Grid.Column="2" Margin="3"/> <Button Content="Right Bottom" Grid.Row="1" Grid.ColumnSpan="2" Grid.Column="2" Margin="3"/> <GridSplitter Grid.Column="1" Grid.RowSpan="2" Width="3" VerticalAlignment="Stretch" HorizontalAlignment="Center" /> </Grid> </Window>
視頻八:使用Canvas面板進行基於坐標的布局 (Canvas面板,Z 順序,InkCanvas元素)
Canvas面板位置:<Canvas Name="canvas1">
<Button Canvas.Left="136" Canvas.Top="20" Content="Button" Width="75"/>
</Canvas>
控件重疊的處理方案:默認情況下都是,Canvas.ZIndex="0" 為0

<Window x:Class="_2014_10_10使用Canvas面板進行基於坐標的布局.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> <Canvas Name="canvas1"> <Button Name="button1" Canvas.Left="136" Canvas.ZIndex="1" Canvas.Top="20" Content="Button" Width="75"/> <DataGrid Height="166" Width="295" Panel.ZIndex="2" > </DataGrid> <Button Canvas.Left="353" Canvas.Top="77" Content="Button" Width="75" Click="Button_Click"/> </Canvas> </Grid> </Window>
InkCanvas 元素 :接收手寫筆的輸入,支持鼠標直接畫圖
<InkCanvas EditingMode="GestureOnly">(根據設置的模式不一樣,有不同的效果。)</InkCanvas>

<Window x:Class="_2014_10_10使用Canvas面板進行基於坐標的布局.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" 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" ></ComboBox> </StackPanel> <InkCanvas EditingMode="None" Grid.Row="1" Name="inkCanvas" Background="#FF1BB444"> <Button InkCanvas.Left="50" InkCanvas.Top="50" Content="Button1"></Button> </InkCanvas> </Grid> </Window>

using System; using System.Collections.Generic; using System.Linq; using System.Text; 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.Shapes; namespace _2014_10_10使用Canvas面板進行基於坐標的布局 { /// <summary> /// Window1.xaml 的交互邏輯 /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { foreach (InkCanvasEditingMode item in Enum.GetValues(typeof(InkCanvasEditingMode))) { EditingMode.Items.Add(item); } EditingMode.SelectedIndex = 0; } private void EditingMode_SelectionChanged(object sender, SelectionChangedEventArgs e) { inkCanvas.EditingMode = (InkCanvasEditingMode)this.EditingMode.SelectedValue; } } }
視頻九:理解路由事件
路由事件出現的三種方式:
1. 直接路由事件
2. 冒泡路由事件:向上傳遞 MouseUp="SomethingClicked" 與隧道路由事件是成對存在的,只是加了一個前綴Preview.

protected int eventCountr = 0; private void SometingClicked(object sender,RoutedEventArgs e ) { eventCountr++; string message = "#" + eventCountr.ToString() + ":\r\n" + " Sender:" + sender.ToString() + ":\r\n" + " Source:" + e.Source + ":\r\n" + " Original Source:" + e.OriginalSource + ":\r\n" + " Event:" + e.RoutedEvent + ":\r\n"; this.listbox1.Items.Add(message); e.Handled = (bool)chkHandle.IsChecked; }
3. 隧道路由事件:向下傳遞 PreviewMouseUp="SomethingClicked" 隧道事件是以Preview開頭。
視頻十:鍵盤輸入(WPF事件類型,鍵盤輸入)
WPF事件類型:五種,a. 生命周期事件(元素初始化,及卸載的時候觸發);鼠標事件(鼠標動作);鍵盤事件(鍵盤動作);手寫筆事件();多點觸控事件。
鍵盤輸入: PreviewKeyDown(隧道路由事件),KeyDown(冒泡路由事件),PreviewTextInput(隧道路由事件),TextInput(接收文本,冒泡),PreviewKeyUp(釋放按鍵,隧道),KeyUp(冒泡)

Window x:Class="_2014_10_11_10鍵盤輸入.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 > <TextBox Focusable="True" TabIndex="0" VerticalAlignment="Top" Grid.ZIndex="20" Height="20" Width="50" Name="TextBox" PreviewKeyDown="KeyEvent" KeyDown="KeyEvent" PreviewTextInput="TextBox_PreviewTextInput" PreviewKeyUp="KeyEvent" KeyUp="KeyEvent" TextChanged="TextBox_TextChanged" ></TextBox> <ListBox VerticalAlignment="Bottom" Name="lstMessages"></ListBox> </Grid> </Window>

using System; using System.Collections.Generic; using System.Text; 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 _2014_10_11_10鍵盤輸入 { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void KeyEvent(object sender, KeyEventArgs e) { string message = " Event:"+ e.RoutedEvent+" " +"Key:"+e.Key; lstMessages.Items.Add(message); } private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { string message = " Event:" + e.RoutedEvent + " " + "Text:" + e.Text; lstMessages.Items.Add(message); } private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { string message = " Event:" + e.RoutedEvent; lstMessages.Items.Add(message); } } }
焦點的獲取及層次: Focusable="True" TabIndex="0"
視頻十一:鼠標輸入(鼠標單擊,捕獲鼠標,鼠標拖放) MouseEventArgs
MouseEnter MouseLeave (直接事件)
PreviewMouseMove(隧道路由事件)
MouseMove(冒泡路由事件)
鼠標單擊:PreviewMouseLeftButtonDown (左鍵) PreviewMouseRightButtonDown(右鍵)
鼠標的鎖定,及鼠標的坐標。

<Window x:Class="_2014_10_11_11鼠標輸入.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 Margin="5"> <Grid.RowDefinitions> <RowDefinition></RowDefinition> <RowDefinition Height="auto"></RowDefinition> <RowDefinition Height="auto"></RowDefinition> </Grid.RowDefinitions> <Rectangle Name="rect" Fill="LightBlue" MouseMove="rect_MouseMove"></Rectangle> <Button Grid.Row="1" Name="cmdCapture" Click="cmdCapture_Click">Capture the Mouse</Button> <TextBlock Name="lblInfo" Grid.Row="2"></TextBlock> </Grid> </Window>

using System; using System.Collections.Generic; using System.Text; 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 _2014_10_11_11鼠標輸入 { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void rect_MouseMove(object sender, MouseEventArgs e) { Point pt = e.GetPosition(this); this.lblInfo.Text=("You are at ")+pt.X+","+pt.Y; } private void cmdCapture_Click(object sender, RoutedEventArgs e) { Mouse.Capture(this.rect);///鎖定鼠標,只有當焦點移開后,才可以繼續操作。 this.cmdCapture.Content = "Mouse is now captured"; } } }
鼠標的拖拽:默認情況下,textbox支持拖拽功能,選中內容+shift(剪切).選中內容+Ctrl(復制). 只需根據如下代碼,可以將lable控件實現拖拽功能。在XAML中,lable控件需要設置允許接收數據。AllowDrop="True"

using System; using System.Collections.Generic; using System.Text; 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.Shapes; namespace _2014_10_11_11鼠標輸入 { /// <summary> /// Window1.xaml 的交互邏輯 /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void lblSoure_MouseDown(object sender, MouseButtonEventArgs e) { Label lbl =(Label) sender; DragDrop.DoDragDrop(lbl,lbl.Content,DragDropEffects.Copy); } private void Label_Drop(object sender, DragEventArgs e) { ((Label)sender).Content = e.Data.GetData(DataFormats.Text); } } }

<Window x:Class="_2014_10_11_11鼠標輸入.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <Grid.RowDefinitions> <RowDefinition ></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <TextBox Text="123456789" Grid.Row="0" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/> <TextBox Text="ABCDEFG" Grid.Row="1" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/> <Label Content="Or this lable" HorizontalAlignment="Left" Margin="161,42,0,0" VerticalAlignment="Top" MouseDown="lblSoure_MouseDown"/> <Label AllowDrop="True" Content="To this lable" HorizontalAlignment="Left" Margin="166,38,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.9,4.038" Grid.Row="1" Drop="Label_Drop"/> </Grid> </Window>
視頻十二:控件類(控件類,背景畫刷和前景畫刷,字體,鼠標光標)
RGB R:紅色,G:綠色,B:藍色。0-255
使用兩種代碼方式來給button賦顏色:
第一種:
button1.Background =new SolidColorBrush(Colors.Red);////背景色
button1.Foreground = System.Windows.SystemColors.ControlDarkBrush;///前景色
第二種:
button1.Background = new SolidColorBrush(Color.FromRgb(100,255,100));
button1.Foreground = System.Windows.SystemColors.ControlDarkBrush;
使用XAML直接在控件上顯示:Background="顏色"
<Button Background="Blue" Name="button1" Content="Button"></Button>
字體屬性:FontFamily 字體的名稱,如:宋體,楷體
FontSize 字體的大小
FontStyle 字體的類型:如斜體
FontWeight 字體的重量:如:加粗
FontStrech 字體的拉伸,及壓縮
TextDecorations="類型" 下划線的類型
<Button Foreground="Red" FontFamily="Times New Roman,Arial" FontSize="36" FontStyle="Italic" FontStretch="Condensed" Background="Blue" Name="button1" Content="Button"></Button>
獲取系統已經安裝的字體:
foreach (FontFamily item in Fonts.SystemFontFamilies)
{
list.Items.Add(item.Source);
}
字體的添加:bayern.tff 首先添加到項目中,設置屬性,生成操作為Resource.
FontFamily="./#bayern"
文本渲染:附加屬性 TextOptions.TextFormattingMode="Display" 文本內容更加清晰。(對於小字體效果更明顯)
光標屬性:繼承框架元素類。
代碼:this.Cursor=Cursors.Wait;
XAML:Cursor="Help"
視頻十三:內容控件(Content屬性,對齊內容,標簽,按鈕,工具提示)
內容控件只能包含一個子元素控件,但是子元素控件里面可以包含多個子元素控件。
Content 屬性:Button控件是內容控件,所以只能包含一個子元素,但是如果子元素是面板容器,子元素內可以包含多個子元素。 對齊的方式:控件對齊 HorizontalAlignment="Left" ;內容對齊 HorizontalContentAlignment="Center" 區分兩種不同的對齊方式。對於image控件中的Source屬性的使用還帶學習。
Label標簽:Targer="" 屬性
<Label Name="label1" Target="{Binding ElementName=textBox1}">Choose _A</Label> ----當按下ALT之后,才會出現快捷鍵方式,按下后,焦點會在txtBox1上面。
<TextBox Name="textBox1" Margin="3">789789</TextBox>
按鈕:a. 屬性 IsCancel="True" ,則在鍵盤上按ESC則會觸發這個按鈕。
b. 屬性IsDefault="True" ,則在鍵盤上按Enter會觸發這個按鈕。
c. 使用CheckBox
<CheckBox IsChecked="{x:Null}" IsThreeState="True"></CheckBox> ////未確定,且可以選擇未確定狀態
<CheckBox IsChecked="True" IsThreeState="True“ ></CheckBox> ////選中狀態,且可以選擇未確定狀態
<CheckBox IsChecked="False" IsThreeState="False“ ></CheckBox> ////未選中狀態,且只能選擇選中跟未選中狀態
d.使用RadioButton 若是在不同的容器中,則不會互相影響,若是在不同的容器中,想要互斥,則需要添加屬性GroupName="rdo",設置相同的組。則會互斥。
工具提示:
簡單提示:屬性 ToolTip="This is my tooltip."
復雜提示:
<ToolTip Background="#60AA4030" > 使用RGB 加了60 則表示透明度。百分之60.
<ToolTip Background="#30AA4030" Placement="Mouse" HorizontalOffset="20" > 表示已鼠標為基准,便宜20像素的地方,出現提示。

<Window x:Class="_2014_10_11_13內容控件.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="584.965" Width="525"> <Grid> <StackPanel Margin="0,0,0,0"> <Button IsDefault="True" IsCancel="True" HorizontalAlignment="Left" HorizontalContentAlignment="Center" Height="20" Name="Button1" Margin="3" Click="Button3_Click" > <Button.ToolTip> <ToolTip Background="#30AA4030" Placement="Mouse" HorizontalOffset="20" > <StackPanel> <TextBlock>Image and text</TextBlock> <Image Source="bin/123.jpg" ></Image> </StackPanel> </ToolTip> </Button.ToolTip> <Button.Content>Button1</Button.Content> </Button> <Button ToolTip="This is my tooltip." IsDefault="True" IsCancel="True" HorizontalAlignment="Left" HorizontalContentAlignment="Center" Content="Button" Height="20" Name="Button2" Margin="3" Click="Button3_Click" /> <Button Height="100" Name="Button3" Margin="3"> <Image Source="bin/123.jpg" ></Image></Button> <Button Height="auto" Name="Button4" Margin="3" > <StackPanel> <TextBlock>Image and text button</TextBlock> <Image Source="bin/123.jpg" Stretch="None"></Image> <TextBlock>Image and text button</TextBlock> </StackPanel> </Button> <Label Name="label1" Target="{Binding ElementName=textBox1}">Choose _A</Label> <TextBox Name="textBox1" Margin="3">789789</TextBox> <CheckBox IsChecked="{x:Null}" IsThreeState="True"></CheckBox> <CheckBox IsChecked="True"></CheckBox> </StackPanel> </Grid> </Window>
Popup控件:需要自己手動添加,與ToolTip 的功能類是。

<Window x:Class="_2014_10_11_13內容控件.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <TextBlock TextWrapping="Wrap"> You can use a Popup to provide a link for a specific <Run TextDecorations="UnderLine" MouseEnter="Run_MouseEnter"> term </Run>of interest. </TextBlock> <Popup Name="popLink" StaysOpen="False" Placement="Mouse" MaxWidth="200" PopupAnimation="Slide" AllowsTransparency="True"> <Border BorderBrush="Beige" BorderThickness="2" Background="White"> <TextBlock Margin="10" TextWrapping="Wrap"> For more informtion,see <Hyperlink Name="lnk" NavigateUri="http://www.baidu.com" Click="Hyperlink_Click">Wikipedia</Hyperlink> </TextBlock> </Border> </Popup> </Grid> </Window>

using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; 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.Shapes; namespace _2014_10_11_13內容控件 { /// <summary> /// Window1.xaml 的交互邏輯 /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Run_MouseEnter(object sender, MouseEventArgs e) { popLink.IsOpen = true; } private void Hyperlink_Click(object sender, RoutedEventArgs e) { Process.Start(((Hyperlink)sender).NavigateUri.ToString()); } } }
視頻十四:特殊容器控件(滾動控件,ScrollViewer)
系統設置及系統提供的方法:滾動到下一個元素 CanContentScroll="True"

using System; using System.Collections.Generic; using System.Text; 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 _2014_10_12_13特殊容器控件 { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { //this.scrollViewer.LineUp();向上一行 //this.scrollViewer.LineDown();向下一行 //this.scrollViewer.PageUp();向上一頁 //this.scrollViewer.PageDown();//向下一頁 //this.scrollViewer.ScrollToHome();//置頂 //this.scrollViewer.ScrollToEnd();//置底 ///自定義滾動 } } }

<Window x:Class="_2014_10_12_13特殊容器控件.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="290.299" Width="471.269"> <Grid> <Grid.RowDefinitions> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <ScrollViewer Grid.Row="1" Margin="10" Name="scrollViewer" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"> <TextBox xml:space="preserve" HorizontalAlignment="Left" Height="110" TextWrapping="Wrap" VerticalAlignment="Top" Width="443" RenderTransformOrigin="0.497,0.405"> Andrew博客園 Andrew博客園 Andrew博客園 Andrew博客園 Andrew博客園 Andrew博客園 Andrew博客園 Andrew博客園 Andrew博客園 </TextBox> </ScrollViewer> <Button Content="lineUp" Name="button1" Click="button1_Click"> </Button> </Grid> </Window>
視頻十五:帶標題的內容控件(GroupBox,TabItem,Expander 三個類)
GroupBox:最簡單的控件

<Window x:Class="_2014_10_13_15帶標題的內容控件.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> <GroupBox Header="123" Margin="5" Name="groupBox1"> <StackPanel> <RadioButton Content="One" Height="16" Name="radioButton1"></RadioButton> <RadioButton Content="Two" Height="16" Name="radioButton2"></RadioButton> <RadioButton Content="Three" Height="16" Name="radioButton3"></RadioButton> <RadioButton Content="Four" Height="16" Name="radioButton4"></RadioButton> <Button Content="Save" Height="23" Name="button1" Margin="3"></Button> </StackPanel> </GroupBox> </Grid> </Window>
TabItem:分頁控件容器

<Window x:Class="_2014_10_13_15帶標題的內容控件.tabItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="tabItem" Height="300" Width="300"> <Grid> <TabControl Margin="3" Name="tabControl1" TabStripPlacement="Left"> <TabItem Header="001" Name="tabItem1"> <StackPanel Name="stackPanel" Margin="3"> <CheckBox Name="checkBox1" Margin="3">Setting One</CheckBox> <CheckBox Name="checkBox2" Margin="3">Setting Two</CheckBox> <CheckBox Name="checkBox3" Margin="3">Setting Three</CheckBox> <Button Content="Button" Name="Button1" Click="Button1_Click"/> </StackPanel> </TabItem> <TabItem Name="tabItem2"> <TabItem.Header> <StackPanel> <TextBlock Margin="3">Image and Text Tab Title</TextBlock> <Image Source="/bin/123.jpg" Stretch="None" Height="20" Width="150"></Image> </StackPanel> </TabItem.Header> </TabItem> </TabControl> </Grid> </Window>

using System; using System.Collections.Generic; using System.Text; 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.Shapes; namespace _2014_10_13_15帶標題的內容控件 { /// <summary> /// tabItem.xaml 的交互邏輯 /// </summary> public partial class tabItem : Window { public tabItem() { InitializeComponent(); } private void Button1_Click(object sender, RoutedEventArgs e) { this.tabItem2.IsSelected = true; } } }
Expander 控件,隱藏部分數據的控件

<Window x:Class="_2014_10_13_15帶標題的內容控件.expander" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="expander" Height="300" Width="300" SizeToContent="Height"> <StackPanel Name="stackPanel1" Margin="3" > <Expander Name="expander1" Height="100" Margin="5" Padding="5" ExpandDirection="Left"> <Button Name="Button1"></Button> </Expander> <Expander Name="expander2" Margin="5" Padding="5"> <ScrollViewer Name="scrollViewer" Margin="3"> <TextBlock TextWrapping="Wrap" >內容內容內容</TextBlock> </ScrollViewer> </Expander> </StackPanel> </Window>
視頻十六:文本控件(多行文本,選擇文本,拼寫檢查,PasswordBox)(TextBox,RichTextBox,PasswordBox)
多行文本:txtbox屬性,有多行自動換行 TextWrapping="Wrap";有滾動條屬性,VerticalScrollBarVisibility="Visible",也有LineUp(),LineDown()等滾動條屬性的方法。
選擇文本:txtbox屬性,SelectionStart屬性(從0開始),SelectionLength(字符長度),SelectedText(選中的屬性)。
拼寫檢查:txtbox屬性,SpellCheck.IsEnabled="True" 僅支持英文輸入法鍵盤設置。
PasswordBox:密碼框控件,PasswordChar="格式" 不支持復制粘帖,純文本對象。

<Window x:Class="_2014_10_13_16文本控件.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.RowDefinitions> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <TextBox SpellCheck.IsEnabled="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible" Name="textBox1" Margin="3,3,3,24.053" MaxLength="50000" Text="Label和TextBlock都是System.Windows.Controls命名空間下的類,但二者的父類並不相同。TextBlock繼承自System.Windows.FrameworkElement,從這個角度講,TextBlock不能稱之為控件(因為它沒有繼承Control類,關於Control類,我會在WPF Unleashed第四章為大家介紹),而Label繼承自System.Windows.ContentControl。FrameworkElement是非常底層的類,它同時也是ContentControl的父類。所以,Label相對TextBlock更加高級一些,它能夠完成TextBlock所無法完成的工作。例如對於Access key的支持,而且我們可以在Label內可以放置任意對象,而TextBlock只能顯示文本。" SelectionChanged="textBox1_SelectionChanged" ></TextBox> <ScrollViewer Foreground="blue" Grid.Row="1" Margin="0,10,0,5" VerticalScrollBarVisibility="Auto"> <StackPanel> <TextBlock>Current Selection: </TextBlock> <TextBlock Name="txtSelection" TextWrapping="Wrap"></TextBlock> </StackPanel> </ScrollViewer> <PasswordBox Grid.Row="2" PasswordChar="8" Height="30" Width="300" ></PasswordBox> </Grid> </Window>

using System; using System.Collections.Generic; using System.Text; 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 _2014_10_13_16文本控件 { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void textBox1_SelectionChanged(object sender, RoutedEventArgs e) { if (this.txtSelection == null) return; this.txtSelection.Text = "Selection from"+this.textBox1.SelectionStart+" to "+this.textBox1.SelectionLength + " is " +this.textBox1.SelectedText; } } }
視頻十七:列表控件(ListBox,ComboBox 下拉列表)
Listbox:控件里面不一定要ListboxItem,直接添加StackPanel也是可以的。

<Window x:Class="_2014_10_13_17列表控件.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> <ListBox Height="311.842" Margin="5,5,5,0" Name="listBox1" VerticalAlignment="Top"> <ListBoxItem> <Image Height="40" Source="/bin/123.jpg"></Image> </ListBoxItem> <ListBoxItem>Blue</ListBoxItem> <ListBoxItem>Yellow</ListBoxItem> <ListBoxItem>Red</ListBoxItem> <ListBoxItem>Green</ListBoxItem> <ListBoxItem>Blue</ListBoxItem> <ListBoxItem>Yellow</ListBoxItem> <ListBoxItem>Red</ListBoxItem> <StackPanel Orientation="Horizontal"> <Image Height="40" Source="/bin/123.jpg"></Image> <Label VerticalContentAlignment="Center">A Happy Face</Label> </StackPanel> <StackPanel Orientation="Horizontal"> <Image Height="40" Source="/bin/123.jpg"></Image> <Label VerticalContentAlignment="Center">Two Happy Face</Label> </StackPanel> <StackPanel Orientation="Horizontal"></StackPanel> </ListBox> </Grid> </Window>
在Listbox中,添加對象,並獲取選中項

<Window x:Class="_2014_10_13_16列表控件.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="*"></RowDefinition> <RowDefinition Height="auto"></RowDefinition> </Grid.RowDefinitions> <ListBox Name="lst" Height="auto" Margin="5" SelectionChanged="lst_SelectionChanged"> <CheckBox Margin="3">Option 1</CheckBox> <CheckBox Margin="3">Option 2</CheckBox> <CheckBox Margin="3">Option 3</CheckBox> </ListBox> <StackPanel Grid.Row="1" Margin="0,10,0,0"> <TextBlock>Current selection:</TextBlock> <TextBlock Name="txtSelection" TextWrapping="Wrap"></TextBlock> <Button Margin="0,10,0,0" Click="Button_Click">Examine All Items </Button> </StackPanel> </Grid> </Window>

using System; using System.Collections.Generic; using System.Text; 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.Shapes; namespace _2014_10_13_16列表控件 { /// <summary> /// Window1.xaml 的交互邏輯 /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void lst_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (lst.SelectedItem == null) return; this.txtSelection.Text = "You chose item at position " + (lst.SelectedIndex+1) +"\t\n Checked state is "+((CheckBox)lst.SelectedItem).IsChecked; } private void Button_Click(object sender, RoutedEventArgs e) { StringBuilder sb = new StringBuilder(); foreach (CheckBox item in lst.Items) { if (item.IsChecked == true) { sb.Append(item.Content); sb.Append(" is checked."); sb.Append("\t\n"); } } txtSelection.Text = sb.ToString(); } } }
視頻十八:基於范圍的控件(Slider 滑動條控件,ProgressBar 進度條控件) 基於最大值與最小值之間。
Slider 控件:類似於,播放聲音的,數值沒有那么准確的重要性。
Ticks="10,30,70" 不規則划分 滑動條
特定的部分設置為,提示部分80-100時候: IsSelectionRangeEnabled="True" SelectionStart="80" SelectionEnd="100"
設置滑動的距離: 最小值 SmallChange="1" 最大值 LargeChange="5"
ProgressBar控件:綠色脈沖 自動滾動:IsIndeterminate="True"

<Window x:Class="_2014_10_13_18基於范圍的控件.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.RowDefinitions> <RowDefinition Height="auto"></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <Slider SmallChange="1" LargeChange="5" IsSelectionRangeEnabled="True" SelectionStart="70" SelectionEnd="100" Maximum="100" Minimum="0" Value="2" TickFrequency="5" TickPlacement="BottomRight" Name="silder1" Margin="5" VerticalAlignment="Top" Height="auto"></Slider> <ProgressBar Name="progressBar" Maximum="100" Minimum="0" Margin="-0.264,129.789,5.264,118.21" Grid.Row="1" Height="40" IsIndeterminate="True"></ProgressBar> <Button HorizontalAlignment="Left" Grid.Row="1" Width="100" Margin="194.736,212.421,0,-4.684" Click="Button_Click"/> </Grid> </Window>

using System; using System.Collections.Generic; using System.Text; 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 _2014_10_13_18基於范圍的控件 { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { this.progressBar.Value += 2; } } }
視頻十九:日期控件(Calendar控件,DatePicker控件)
Calendar 日歷控件: <Calendar DisplayMode="Month">默認情況下是模式是Month</Calendar>

<Window x:Class="_2014_10_13_19日期控件.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> <Calendar IsTodayHighlighted="True" SelectionMode="MultipleRange" Name="calendar" DisplayMode="Month" DisplayDateStart="2014-10-1" DisplayDateEnd="2014-10-31" FirstDayOfWeek="Monday" SelectedDatesChanged="Calendar_SelectedDatesChanged"></Calendar> <Button Content="Button" HorizontalAlignment="Left" Margin="208,216,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/> </Grid> </Window>

using System; using System.Collections.Generic; using System.Text; 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 _2014_10_13_19日期控件 { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Calendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e) { //this.Title = this.calendar.SelectedDate.ToString(); //this.Title = this.calendar.SelectedDates.ToString();////存多個時期,是一個集合 } private void Button_Click(object sender, RoutedEventArgs e) { string s = ""; for (int i = 0; i < this.calendar.SelectedDates.Count; i++) { s += this.calendar.SelectedDates[i].ToShortDateString() + " "; } this.Title=s; } } }
DatePicker控件:
<DatePicker Height="25" Width="100" IsDropDownOpen="False" Margin="198,183,219,112" DateValidationError="DatePicker_DateValidationError" ></DatePicker>
private void DatePicker_DateValidationError(object sender, DatePickerDateValidationErrorEventArgs e)
{
////用戶輸入非法的數據
MessageBox.Show(e.Text+" is not a valid value beause."+e.Exception.Message);
}
視頻二十:Application類
創建Application對象,其實App.xaml+App.xaml.cs 倆個加起來的功能與如下的代碼是一樣的效果。

using System; using System.Collections.Generic; using System.Text; using System.Windows; namespace _2014_10_13_20Application類 { class Startup { [STAThread] public static void Main() { Application app = new Application(); MainWindow win = new MainWindow(); app.Run(win); } } }
派生一個自定義的Application類 :App.xaml.cs 里面的App類就是了。
應用程序的關閉方式:ShutdownMode 關閉模式。
StartupUri="MainWindow.xaml" ShutdownMode="OnLastWindowClose"> ////默認模式,可以不寫
應用程序事件: Application 的事件,有兩種方法,一種是單純的直接使用事件,第二種是重寫受保護的方法。

using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Windows; namespace _2014_10_13_20Application類 { /// <summary> /// App.xaml 的交互邏輯 /// </summary> public partial class App : Application { private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { } ///重寫受保護的方法 protected override void OnSessionEnding(SessionEndingCancelEventArgs e) { base.OnSessionEnding(e); e.Cancel = true;////阻止關閉系統 MessageBox.Show("無法注銷或關閉系統"); } } }

<Application x:Class="_2014_10_13_20Application類.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml" ShutdownMode="OnLastWindowClose" DispatcherUnhandledException="Application_DispatcherUnhandledException"> <Application.Resources> </Application.Resources> </Application>
視頻二十一:Application 類的任務(顯示初始界面,處理命令行參數,訪問當前Application對象,在窗口之間進行交互)
顯示初始頁面:添加一張圖片,設置屬性,生成操作為SplashScreen,則在窗口第一次運行的時候,則會顯示該圖片(300毫秒)。
處理命令行參數:加載TextFile.txt文檔。
首先添加TextFile.txt文檔到bin目錄下,設置文檔的屬性:始終復制。
在App.xaml將 StartupUri="MainWindow.xaml"替換成Startup="Application_Startup"事件方法
在項目的屬性,調試的命令行參數填寫文檔的名稱:TextFile.txt

<Application x:Class="_2014_10_14_21Application任務.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Startup="Application_Startup" > <Application.Resources> </Application.Resources> </Application>

////App.xaml.cs using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.IO; using System.Windows; namespace _2014_10_14_21Application任務 { /// <summary> /// App.xaml 的交互邏輯 /// </summary> public partial class App : Application { private void Application_Startup(object sender, StartupEventArgs e) { MainWindow win = new MainWindow(); if (e.Args.Length > 0) { string file=e.Args[0]; if(File.Exists(file)) { win.LoadFile(file); } } win.Show(); } } }

using System; using System.Collections.Generic; using System.Text; 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 _2014_10_14_21Application任務 { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public void LoadFile(string path) { this.Content = System.IO.File.ReadAllText(path); this.Title = path; } } }
訪問當前Application主窗口的對象: Application.Current.MainWindow
一次啟動倆個窗口, Application.Current.MainWindow來辨別主窗口。
windows集合:
private void Button_Click(object sender, RoutedEventArgs e)
{
///MessageBox.Show("The main window is "+ Application.Current.MainWindow.Title);
foreach (Window item in Application.Current.Windows)////Windows集合
{
MessageBox.Show(item.Title+" is opened.");
}
}


////App.xaml.cs using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.IO; using System.Windows; namespace _2014_10_14_21Application任務 { /// <summary> /// App.xaml 的交互邏輯 /// </summary> public partial class App : Application { //private void Application_Startup(object sender, StartupEventArgs e) //{ // MainWindow win = new MainWindow(); // if (e.Args.Length > 0) // { // string file=e.Args[0]; // if(File.Exists(file)) // { // win.LoadFile(file); // } // } // win.Show(); //} private List<Document> documents = new List<Document>(); public List<Document> Documents { get { return documents; } set { documents = value; } } } }

using System; using System.Collections.Generic; using System.Linq; using System.Text; 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.Shapes; namespace _2014_10_14_21Application任務 { /// <summary> /// Window1.xaml 的交互邏輯 /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { ///MessageBox.Show("The main window is "+ Application.Current.MainWindow.Title); //foreach (Window item in Application.Current.Windows)////Windows集合 //{ // MessageBox.Show(item.Title+" is opened."); //} Document doc = new Document(); doc.Owner = this; doc.Show(); ((App)Application.Current).Documents.Add(doc); } private void Button_Click_1(object sender, RoutedEventArgs e) { foreach (Document item in ((App)Application.Current).Documents) { item.Content = "Refreshed at " + DateTime.Now.ToLongTimeString() + "."; MessageBox.Show(item.Title + " is opened."); } } } }
視頻二十二:單實例應用程序(創建單實例應用程序包裝器) office word是單實例,文本txt是多實例。
實現單實例應用程序:

//WpfApp.cs using System; using System.Collections.Generic; using System.Text; namespace _2014_10_14_22單實例應用程序 { class WpfApp:System.Windows.Application { protected override void OnStartup(System.Windows.StartupEventArgs e) { base.OnStartup(e); showWindow(); } public void showWindow() { MainWindow win = new MainWindow(); win.Show(); } } }

using System; //Startup.cs using System.Collections.Generic; using System.Text; namespace _2014_10_14_22單實例應用程序 { class Startup { [STAThread] public static void Main(string[] args) { //WpfApp app = new WpfApp(); //app.Run(); SingleInstanceApplicationWrapper wrapper = new SingleInstanceApplicationWrapper(); wrapper.Run(args); } } }

////SingleInstanceApplicationWrapper.cs using System; using System.Collections.Generic; using System.Text; namespace _2014_10_14_22單實例應用程序 { class SingleInstanceApplicationWrapper:Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase { public SingleInstanceApplicationWrapper() { this.IsSingleInstance = true; } private WpfApp app; protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs) { //return base.OnStartup(eventArgs); app = new WpfApp(); app.Run(); return false; } protected override void OnStartupNextInstance(Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs eventArgs) { base.OnStartupNextInstance(eventArgs); app.showWindow(); } } }
視頻二十三:程序集資源,二進制資源(添加資源,內容文件)
舉例說明:添加圖片文件
添加資源:默認情況下,設置圖片文件的屬性,復制到輸出目錄:不復制,生成操作:Resource
內容文件:設置圖片文件的屬性,復制到輸出目錄:始終復制,生成操作:內容
視頻二十四:將元素綁定到一起(綁定表達式,綁定錯誤,綁定模式,使用代碼創建綁定多綁定,綁定更新)
例子:FontSize="{Binding ElementName=silder1,Path=Value,Mode=TwoWay}
綁定表達式:FontSize="{Binding ElementName=silder1,Path=Value,Mode=TwoWay}
綁定錯誤:屬性錯誤的時候,不會提示錯誤,只是沒有任何改變罷了。
綁定模式:Mode=TwoWay 雙向改變
使用代碼創建綁定多綁定:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Binding binding = new Binding();
binding.Source = this.silder1;
binding.Path = new PropertyPath("Value");
binding.Mode = BindingMode.TwoWay;
this.textBlock2.SetBinding(TextBlock.FontSizeProperty,binding);
}
取消綁定:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
BindingOperations.ClearAllBindings(this.textBlock2);
}
綁定立即更新:UpdateSourceTrigger=PropertyChanged
<TextBox Margin="3" Height=" 23" Name="textBox1" Width="120" Text="{Binding ElementName=textBlock2,Path=FontSize,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox>

<Window x:Class="_2014_10_18_24將元素綁定到一起.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> <StackPanel Margin="5" Name="stackPanel1"> <Slider Height="auto" Name="silder1" Margin="3" Minimum="1" Maximum="40" Value="10" TickPlacement="TopLeft" TickFrequency="1" IsSnapToTickEnabled="True"></Slider> <TextBlock Name="textBlock1" Text="Simple Text" Margin="10" FontSize="{Binding ElementName=silder1,Path=Value,Mode=TwoWay}"/> <TextBlock Name="textBlock2" Text="Simple Text" Margin="10" Foreground="{Binding ElementName=listBox1,Path=SelectedItem.Tag}"/> <Button Content="Button" Margin="5" Width="75" Click="Button_Click"/> <Button Content="Cancel Binding" Margin="216,5" Width="75" Click="Button_Click_1"/> <ListBox Margin="10" Height="100" Name="listBox1"> <ListBoxItem Tag="Blue">Blue</ListBoxItem> <ListBoxItem Tag="DarkBlue">Blue</ListBoxItem> <ListBoxItem Tag="lightBlue">light Blue</ListBoxItem> </ListBox> <TextBox Margin="3" Height=" 23" Name="textBox1" Width="120" Text="{Binding ElementName=textBlock2,Path=FontSize,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox> </StackPanel> </Grid> </Window>

using System; using System.Collections.Generic; using System.Text; 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 _2014_10_18_24將元素綁定到一起 { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { //this.silder1.Value = 30; this.textBlock1.FontSize = 30; } private void Window_Loaded(object sender, RoutedEventArgs e) { Binding binding = new Binding(); binding.Source = this.silder1; binding.Path = new PropertyPath("Value"); binding.Mode = BindingMode.TwoWay; this.textBlock2.SetBinding(TextBlock.FontSizeProperty,binding); } private void Button_Click_1(object sender, RoutedEventArgs e) { BindingOperations.ClearAllBindings(this.textBlock2); } } }
視頻二十五:綁定到非元素對象(Source屬性,RelativeSource屬性,DataContext屬性)
Source屬性:

<Window x:Class="_2014_10_18_25綁定到非元素對象.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"> <Window.Resources> <FontFamily x:Key="CustomFont">Calibri</FontFamily> <FontFamily x:Key="CustomFont1">Calibri1</FontFamily> </Window.Resources> <Grid> <StackPanel Margin="5" Name="stackPanel1"> <TextBlock Name="textBlock1" Text="{Binding Source={x:Static SystemFonts.IconFontFamily},Path=Source}"></TextBlock> <TextBlock Name="textBlock2" Text="{Binding Source={StaticResource CustomFont},Path=Source}"></TextBlock> </StackPanel> </Grid> </Window>
RelativeSource屬性:
<RelativeSource Mode="FindAncestor">

<Window x:Class="_2014_10_18_25綁定到非元素對象.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"> <Window.Resources> <FontFamily x:Key="CustomFont">Calibri</FontFamily> <FontFamily x:Key="CustomFont1">Calibri1</FontFamily> </Window.Resources> <Grid> <StackPanel Name="StackPaenlOut"> <StackPanel Margin="5" Name="stackPanel1"> <TextBlock Name="textBlock1" Text="{Binding Source={x:Static SystemFonts.IconFontFamily},Path=Source}"></TextBlock> <TextBlock Name="textBlock2" Text="{Binding Source={StaticResource CustomFont},Path=Source}"></TextBlock> <TextBlock Name="textBlock3" Margin="5"> <TextBlock.Text> <Binding Path="Title"> <Binding.RelativeSource> <RelativeSource Mode="FindAncestor" AncestorType="{x:Type Window }"></RelativeSource> </Binding.RelativeSource> </Binding> </TextBlock.Text> </TextBlock> <TextBlock Name="textBlock4" Margin="5" Text="{Binding Path=Name,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type StackPanel},AncestorLevel=2}}"> </TextBlock> </StackPanel> </StackPanel> </Grid> </Window>
DataContext屬性:DataContext="{x:Static SystemFonts.IconFontFamily} 添加在上一層的元素屬性中,可以減少子元素多次使用的,相當於統一聲明功能。

<Window x:Class="_2014_10_18_25綁定到非元素對象.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"> <Window.Resources> <FontFamily x:Key="CustomFont">Calibri</FontFamily> <FontFamily x:Key="CustomFont1">Calibri1</FontFamily> </Window.Resources> <Grid> <StackPanel Name="StackPaenlOut"> <StackPanel Margin="5" Name="stackPanel1" DataContext="{x:Static SystemFonts.IconFontFamily}"> <TextBlock Name="textBlock1" Text="{Binding Source={x:Static SystemFonts.IconFontFamily},Path=Source}"></TextBlock> <TextBlock Name="textBlock2" Text="{Binding Source={StaticResource CustomFont},Path=Source}"></TextBlock> <TextBlock Name="textBlock3" Margin="5"> <TextBlock.Text> <Binding Path="Title"> <Binding.RelativeSource> <RelativeSource Mode="FindAncestor" AncestorType="{x:Type Window }"></RelativeSource> </Binding.RelativeSource> </Binding> </TextBlock.Text> </TextBlock> <TextBlock Name="textBlock4" Margin="5" Text="{Binding Path=Name,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type StackPanel},AncestorLevel=2}}"> </TextBlock> <TextBlock Name="textBlock5" Text="{Binding Path=Source}"></TextBlock> <TextBlock Name="textBlock6" Text="{Binding Source={x:Static SystemFonts.IconFontFamily},Path=LineSpacing}"></TextBlock> <TextBlock Name="textBlock7" Text="{Binding Source={x:Static SystemFonts.IconFontFamily},Path=FamilyTypefaces[0].Style}"></TextBlock> </StackPanel> </StackPanel> </Grid> </Window>
視頻二十六:資源基礎(WPF資源,資源集合,資源層次,靜態資源和動態資源,通過代碼訪問,應用程序資源,系統資源)
資源定義在引用之前定義。

<Window x:Class="_2014_10_21_26資源基礎.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"> <Window.Resources> <ImageBrush x:Key="TitleBrush" TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 32 32" ImageSource="bin\001.jpg" ></ImageBrush> </Window.Resources> <StackPanel Name="stackPanel1" Margin="3"> <Button Name="button1" Background="{StaticResource TitleBrush}" Margin="3" Content="A Tiled Button" FontSize="14" Padding="5"></Button> <Button Name="button2" Margin="3" Content="Button" FontSize="14" Padding="5"> <Button.Resources> <ImageBrush x:Key="TitleBrush" TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 32 32" ImageSource="bin\001.jpg" ></ImageBrush> </Button.Resources> <Button.Background> <StaticResource ResourceKey="TitleBrush"></StaticResource> </Button.Background> </Button> <Button Name="button3" Margin="3" Background="{DynamicResource TitleBrush}" Content="Button" FontSize="14" Padding="5"></Button> </StackPanel> </Window>
視頻二十七:資源字典(創建資源字典,使用資源字典,在程序集之間共享資源)

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ImageBrush x:Key="TileBrush1" TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 32 32" Opacity="0.3" ImageSource="\Debug\001.jpg"></ImageBrush> <ImageBrush x:Key="TileBrush2" TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 32 32" Opacity="0.3" ImageSource="\Debug\001.jpg"></ImageBrush> </ResourceDictionary>

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> </ResourceDictionary>

<Window x:Class="_2014_11_03_27資源字典.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"> <StackPanel Name="stackPanel1" Margin="5"> <Button Content="Button" Name="button1" Margin="5" Padding="5" FontSize="14" Background="{DynamicResource TileBrush1}"></Button> <Button Content="Button" Name="button2" Margin="5" Padding="5" FontSize="14" Background="{DynamicResource TileBrush2}"></Button> <Button Content="Button" Name="button3" Margin="5" Padding="5" FontSize="14"></Button> </StackPanel> </Window>

using System; using System.Collections.Generic; using System.Linq; using System.Text; 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 _2014_11_03_27資源字典 { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { ////通過編譯類庫,添加引用ResourceLibray,則使用代碼添加使用資源 ResourceDictionary rd = new ResourceDictionary(); rd.Source = new Uri("ResourceLibray;component/ResourceDictionary1.xaml",UriKind.Relative); this.button3.Background = (Brush)rd["TitleBrush1"]; //// } } }
視頻二十八:樣式基礎類似於CSS(樣式基礎,創建樣式,設置屬性,關聯事件處理程序,多層樣式,通過類型自動應用樣式)
首先是傳統的方式,不僅沒有簡化,而且還增加了復雜度。

<Window x:Class="_2014_11_03_28樣式基礎.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" Title="MainWindow" Height="350" Width="525" > <Window.Resources> <FontFamily x:Key="ButtonFontFamily" >Times New Roman</FontFamily> <sys:Double x:Key="ButtonFontSize">18</sys:Double> <FontWeight x:Key="ButtonFontWeight">Bold</FontWeight> </Window.Resources> <StackPanel Name="stackPanel1" Margin="5"> <Button Name="button1" Content="A Customaized Button" Margin="5" Padding="5" FontFamily="{StaticResource ButtonFontFamily}" FontSize="{StaticResource ButtonFontSize}" FontWeight="{StaticResource ButtonFontWeight}"></Button> <TextBlock Margin="5">Noraml Conent</TextBlock> <Button Margin="5" Padding="5">A normal Button</Button> <TextBlock Margin="5">More Noraml Content</TextBlock> <Button Margin="5" Padding="5" FontFamily="{StaticResource ButtonFontFamily}" FontSize="{StaticResource ButtonFontSize}" FontWeight="{StaticResource ButtonFontWeight}">Another Customized Button</Button> </StackPanel> </Window>
通過創建樣式:

<Window x:Class="_2014_11_03_28樣式基礎.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" Title="MainWindow" Height="350" Width="525" > <Window.Resources> <FontFamily x:Key="ButtonFontFamily" >Times New Roman</FontFamily> <sys:Double x:Key="ButtonFontSize">18</sys:Double> <FontWeight x:Key="ButtonFontWeight">Bold</FontWeight> <Style x:Key="BigFontButtonStyle" > <Setter Property="Control.FontFamily" Value="Times New Roman"></Setter> <!--<Setter Property="Control.FontSize" Value="18"></Setter>--> <!--<Setter Property="Button.FontSize" Value="18"></Setter> 從中可以看到雖然是分別設置了屬性,但是只以最后設置的屬性為准。 <Setter Property="TextBlock.FontSize" Value="10"></Setter>--> <Setter Property="Control.FontWeight" Value="Bold"></Setter> <Setter Property="Control.Background"> <Setter.Value> <ImageBrush TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 32 32" Opacity="0.3" ImageSource="bin\001.jpg"></ImageBrush> </Setter.Value> </Setter> </Style> </Window.Resources> <StackPanel Name="stackPanel1" Margin="5"> <Button Name="button1" Content="A Customaized Button" Margin="5" Padding="5" FontFamily="{StaticResource ButtonFontFamily}" FontSize="{StaticResource ButtonFontSize}" FontWeight="{StaticResource ButtonFontWeight}"></Button> <TextBlock Margin="5">Noraml Conent</TextBlock> <Button Margin="5" Padding="5">A normal Button</Button> <TextBlock Margin="5" Padding="5" Style="{StaticResource BigFontButtonStyle}">More Noraml Content</TextBlock> <Button Margin="5" Padding="5" FontFamily="{StaticResource ButtonFontFamily}" FontSize="{StaticResource ButtonFontSize}" FontWeight="{StaticResource ButtonFontWeight}">Another Customized Button</Button> <Button Margin="5" Padding="5" Style="{StaticResource BigFontButtonStyle}">Another Customized Button</Button> </StackPanel> </Window>
關聯事件處理程序

<Window x:Class="_2014_11_03_28樣式基礎.EventSetter" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="EventSetter" Height="300" Width="300"> <Window.Resources> <Style x:Key="MouseOverHighLight"> <Setter Property="TextBlock.Padding" Value="5"></Setter> <EventSetter Event="FrameworkElement.MouseEnter" Handler="element_MouseEnter"></EventSetter> <EventSetter Event="FrameworkElement.MouseLeave" Handler="element_MouseLeave"></EventSetter> </Style> </Window.Resources> <StackPanel Name="stackPanel"> <TextBlock Style="{StaticResource MouseOverHighLight}">Hover over me.</TextBlock> <TextBlock Padding="5">Don't bother with me.</TextBlock> <TextBlock Style="{StaticResource MouseOverHighLight}">Hover over me.</TextBlock> </StackPanel> </Window>

using System; using System.Collections.Generic; using System.Linq; using System.Text; 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.Shapes; namespace _2014_11_03_28樣式基礎 { /// <summary> /// EventSetter.xaml 的交互邏輯 /// </summary> public partial class EventSetter : Window { public EventSetter() { InitializeComponent(); } private void element_MouseEnter(object sender,MouseEventArgs e) { ((TextBlock)sender).Background = new SolidColorBrush(Colors.LightBlue); } private void element_MouseLeave(object sender, MouseEventArgs e) { ((TextBlock)sender).Background = null; } } }
通過類型自動應用樣式

<Window x:Class="_2014_11_03_28樣式基礎.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" Title="MainWindow" Height="350" Width="525" > <Window.Resources> <FontFamily x:Key="ButtonFontFamily" >Times New Roman</FontFamily> <sys:Double x:Key="ButtonFontSize">18</sys:Double> <FontWeight x:Key="ButtonFontWeight">Bold</FontWeight> <Style x:Key="BigFontButtonStyle" > <Setter Property="Control.FontFamily" Value="Times New Roman"></Setter> <!--<Setter Property="Control.FontSize" Value="18"></Setter>--> <!--<Setter Property="Button.FontSize" Value="18"></Setter> 從中可以看到雖然是分別設置了屬性,但是只以最后設置的屬性為准。 <Setter Property="TextBlock.FontSize" Value="10"></Setter>--> <Setter Property="Control.FontWeight" Value="Bold"></Setter> <Setter Property="Control.Background"> <Setter.Value> <ImageBrush TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 32 32" Opacity="0.3" ImageSource="bin\001.jpg"></ImageBrush> </Setter.Value> </Setter> </Style> <Style x:Key="EmphasizeBigFontButtonStyle" BasedOn="{StaticResource BigFontButtonStyle}"> <!--BasedOn繼承了上一個style--> <Setter Property="Control.Foreground" Value="White"></Setter> <Setter Property="Control.Background" Value="LightBlue"></Setter> </Style> <Style TargetType="Button" BasedOn="{StaticResource BigFontButtonStyle}"> <!--全部的Button使用這個樣式,使用Style="{x:Null}",則不啟用--> <Setter Property="Control.Foreground" Value="White"></Setter> <Setter Property="Control.Background" Value="LightBlue"></Setter> </Style> </Window.Resources> <StackPanel Name="stackPanel1" Margin="5"> <Button Name="button1" Content="A Customaized Button" Margin="5" Padding="5" Style="{x:Null}" FontFamily="{StaticResource ButtonFontFamily}" FontSize="{StaticResource ButtonFontSize}" FontWeight="{StaticResource ButtonFontWeight}"></Button> <TextBlock Margin="5">Noraml Conent</TextBlock> <Button Margin="5" Padding="5">A normal Button</Button> <TextBlock Margin="5" Padding="5" Style="{StaticResource BigFontButtonStyle}">More Noraml Content</TextBlock> <Button Margin="5" Padding="5" FontFamily="{StaticResource ButtonFontFamily}" FontSize="{StaticResource ButtonFontSize}" FontWeight="{StaticResource ButtonFontWeight}">Another Customized Button</Button> <Button Margin="5" Padding="5" Style="{StaticResource EmphasizeBigFontButtonStyle}">Another Customized Button</Button> </StackPanel> </Window>
視頻二十九:觸發器(簡單觸發器,事件觸發器)
簡單觸發器

<Window x:Class="_2014_11_03_29觸發器.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"> <Window.Resources> <Style x:Key="BigFontButton" > <Style.Setters> <Setter Property="Control.FontFamily" Value="Times New Roman"></Setter> <Setter Property="Control.FontSize" Value="32"></Setter> </Style.Setters> <Style.Triggers> <!--<Trigger Property="Button.IsPressed" Value="True"> <Setter Property="Control.Foreground" Value="Blue"></Setter> </Trigger> <Trigger Property="Control.IsFocused" Value="True"> <Setter Property="Control.Foreground" Value="DarkRed"></Setter> </Trigger>--> <MultiTrigger> <MultiTrigger.Conditions><!--表示多個條件為真的時候,才觸發事件--> <Condition Property="Control.IsFocused" Value="True" ></Condition> <Condition Property="Control.IsMouseOver" Value="True" ></Condition> </MultiTrigger.Conditions> <MultiTrigger.Setters > <Setter Property="Control.Foreground" Value="Blue"></Setter> </MultiTrigger.Setters> </MultiTrigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <Button Height="100" Style="{StaticResource BigFontButton}" Margin="5" Name="button1" Content="Button"></Button> <TextBox HorizontalAlignment="Left" Height="23" Margin="206,271,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/> </Grid> </Window>
事件觸發器

<Window x:Class="_2014_11_03_29觸發器.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"> <Window.Resources> <Style x:Key="BigFontButton" > <Style.Setters> <Setter Property="Control.FontFamily" Value="Times New Roman"></Setter> <Setter Property="Control.FontSize" Value="32"></Setter> </Style.Setters> <Style.Triggers> <!--<Trigger Property="Button.IsPressed" Value="True"> <Setter Property="Control.Foreground" Value="Blue"></Setter> </Trigger> <Trigger Property="Control.IsFocused" Value="True"> <Setter Property="Control.Foreground" Value="DarkRed"></Setter> </Trigger>--> <!--<MultiTrigger> <MultiTrigger.Conditions>--><!--表示多個條件為真的時候,才觸發事件--><!-- <Condition Property="Control.IsFocused" Value="True" ></Condition> <Condition Property="Control.IsMouseOver" Value="True" ></Condition> </MultiTrigger.Conditions> <MultiTrigger.Setters > <Setter Property="Control.Foreground" Value="Blue"></Setter> </MultiTrigger.Setters> </MultiTrigger>--> <EventTrigger RoutedEvent="Mouse.MouseEnter"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimation Duration="0:0:0.2" Storyboard.TargetProperty="FontSize" To="48"></DoubleAnimation> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> <EventTrigger RoutedEvent="Mouse.MouseLeave"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimation Duration="0:0:0.5" Storyboard.TargetProperty="FontSize" ></DoubleAnimation> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <Button Height="100" Style="{StaticResource BigFontButton}" Margin="5" Name="button1" Content="Button"></Button> <TextBox HorizontalAlignment="Left" Height="23" Margin="206,271,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/> </Grid> </Window>
視頻三十:行為(行為,獲取行為支持,創建行為,使用行為) Expression Blend 3 SDK (http://tinyurl.com/kkp4g8)
由於涉及到類庫,未能實現全部的代碼。

<Window x:Class="_2014_11_03_30行為.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 Name="canvas1"> <Rectangle Canvas.Left="10" Canvas.Top="10" Fill="Yellow" Width="80" Height="60"></Rectangle> <Ellipse Canvas.Left="80" Canvas.Top="70" Name="ellipse1" Fill="blue" Width="80" Height="60"></Ellipse> </Canvas> </Window>
視頻三十一:形狀(理解形狀,Shape類,矩形和橢圓,使用Viewbox控件縮放形狀,直線,折線,多邊形,直線線帽和直線交點,點划線)
矩形和橢圓代碼:

<Window x:Class="_2014_11_18_31形狀.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.RowDefinitions> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <Rectangle RadiusX="10" RadiusY="100" Height="100" Name="rectangle1" Fill="Red" Stroke="Black" Width="200"> </Rectangle> <Ellipse Grid.Row="1" Fill="Yellow" Stroke="Black" Margin="10" Stretch="Uniform"></Ellipse> </Grid> </Window>
使用Viewbox控件縮放形狀代碼:

<Window x:Class="_2014_11_18_31形狀.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.RowDefinitions> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <!--<Rectangle RadiusX="10" RadiusY="100" Height="100" Name="rectangle1" Fill="Red" Stroke="Black" Width="200"> </Rectangle> <Ellipse Grid.Row="1" Fill="Yellow" Stroke="Black" Margin="10" Stretch="Uniform"></Ellipse>--> <TextBlock>The first row of a </TextBlock> <Viewbox Grid.Row="1" HorizontalAlignment="Left"> <Canvas Width="200" Height="150"> <Rectangle Fill="Yellow" Stroke="blue" Canvas.Left="30" Canvas.Top=" 40" Height="60" Width="100" HorizontalAlignment="Left"></Rectangle> <Ellipse Fill="Yellow" Stroke="blue" Canvas.Left="10" Canvas.Top="50" Width="100" Height="50" HorizontalAlignment="Left"></Ellipse> </Canvas> </Viewbox> </Grid> </Window>
直線,折線,多邊形代碼:

<Window x:Class="_2014_11_18_31形狀.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.RowDefinitions> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <!--<Rectangle RadiusX="10" RadiusY="100" Height="100" Name="rectangle1" Fill="Red" Stroke="Black" Width="200"> </Rectangle> <Ellipse Grid.Row="1" Fill="Yellow" Stroke="Black" Margin="10" Stretch="Uniform"></Ellipse>--> <TextBlock>The first row of a </TextBlock> <Viewbox Grid.Row="1" HorizontalAlignment="Left"> <Canvas Width="200" Height="150"> <Line Stroke="red" X1="0" Y1="0" X2="10" Y2="100" Canvas.Left="150" Canvas.Top="20"></Line><!--直線--> <Rectangle Fill="Yellow" Stroke="blue" Canvas.Left="30" Canvas.Top=" 40" Height="60" Width="100" HorizontalAlignment="Left"></Rectangle><!--矩形--> <Ellipse Fill="Yellow" Stroke="blue" Canvas.Left="10" Canvas.Top="50" Width="100" Height="50" HorizontalAlignment="Left"></Ellipse><!--橢圓--> <Polyline Stroke="Blue" Points="5,5 15,50, 50 ,80 100,1"></Polyline><!--折線--> <Polygon Stroke="Blue" Points="10,10 15,50, 50 ,80 100,1" Canvas.Left="100" ></Polygon><!--多邊形--> </Canvas> </Viewbox> </Grid> </Window>
直線線帽和直線交點:
<Line StrokeThickness="15" StrokeStartLineCap="Triangle" StrokeEndLineCap="Round" Stroke="red" X1="0" Y1="0" X2="10" Y2="100" Canvas.Left="150" Canvas.Top="20"></Line><!--直線-->
其中,StrokeThickness="15" 設置線的粗細。
StrokeStartLineCap="Triangle" 設置起點的樣式
StrokeEndLineCap="Round" 設置終點的樣式
點划線代碼:
<Polyline StrokeDashArray="1 5" StrokeThickness="2" Stroke="Blue" Points="5,5 15,50, 50 ,80 100,1"></Polyline><!--折線-->
其中,StrokeDashArray="1 5" 1 是使用實線的位置, 5是虛線的位置。 StrokeThickness="15" 設置線的粗細。