WPF学习笔记--基础篇

基础部分

一、常用布局容器

1 StackPanel

主要用于垂直或水平排列元素、在容器的可用尺寸内放置有限个元素,元素
尺寸总和不能超过StackPanel的尺寸, 否则超出的部分不可见。默认从上往下排列

        <StackPanel>
            <Button Width="100" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="100" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="100" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="100" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="100" Height="100" Content="按钮" FontSize="40"/>
        </StackPanel>

2 WrapPanel

默认排列方向与StackPanel相反、WrapPanel的Orientation(布局方向)默认为Horizontal(水平)
WrapPanel具备StackPanel的功能基础上具备在尺寸变更后自动适应容器的宽高进行换行换列处理。

        <WrapPanel>
            <Button Width="150" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="150" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="150" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="150" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="150" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="150" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="150" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="150" Height="100" Content="按钮" FontSize="40"/>
        </WrapPanel>

3 DockPanel

默认DockPanel中的元素具备DockPanel.Dock属性, 该属性为枚举具备: Top、Left、Right、Bottom。
默认情况下, DockPanel中的元素不添加DockPanel.Dock属性, 则系统则会默认添加 Left。
DockPanel有一个LastChildFill属性, 该属性默认为true, 该属性作用为, 当容器中的最后一个元素默认该元素填充DockPanel所有空间。

        <DockPanel LastChildFill="True">
            <Button Width="100" Height="100" Content="左" FontSize="40" DockPanel.Dock="Left"/>
            <Button Width="100" Height="100" Content="上" FontSize="40" DockPanel.Dock="Top"/>
            <Button Width="100" Height="100" Content="右" FontSize="40" DockPanel.Dock="Right"/>
            <Button Width="100" Height="100" Content="下" FontSize="40" DockPanel.Dock="Bottom"/>
            <Button Width="100" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="100" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="100" Height="100" Content="按钮" FontSize="40"/>
            <Button Width="100" Height="100" Content="按钮" FontSize="40" />
        </DockPanel>

  

4 Grid

Grid具备分割空间的能力。
1:RowDefinitions / ColumnDefinitions 用于给Grid分配行与列。
2:ColumnSpan / RowSpan 则用于设置空间元素的 跨列与跨行。

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>//第1行
            <RowDefinition/>//第2行
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>//第1列
            <ColumnDefinition/>//第2列
        </Grid.ColumnDefinitions>
        //索引是从0开始的, 00  01  10  11分别表示位置
        //第1行第1列,第1行第2列,第2行第1列,第2行第2列
        <StackPanel Grid.Row="0" Grid.Column="0" Background="SkyBlue"/>
        <StackPanel Grid.Row="0" Grid.Column="1" Background="Yellow"/>
        <StackPanel Grid.Row="1" Grid.Column="0" Background="Gray"/>
        <StackPanel Grid.Row="1" Grid.Column="1" Background="Orange"/>
        <Button Grid.ColumnSpan="2" Grid.RowSpan="2" Width="100" Height="100" 
        FontSize="40">按钮</Button>
    </Grid>

5 Canvas

用于绘制和定位的画布,布局、绘图、事件处理等等

    <Canvas>
        <Ellipse Width="100" Height="100" Fill="Red" Canvas.Left="100" Canvas.Top="100"/>
        <Rectangle Width="100" Height="200" Fill="Green" Canvas.Right="100" Canvas.Bottom="100"/>
        <Button Width="150" Height="60" Content="按钮" FontSize="40" Canvas.Left="330" Canvas.Top="150"/>
    </Canvas>

6 UniformGrid

内部控件自动均分空间

    <UniformGrid>
        <Button Width="200" Height="70" Content="按钮" FontSize="40"/>
        <Button Width="200" Height="70" Content="按钮" FontSize="40"/>
        <Button Width="200" Height="70" Content="按钮" FontSize="40"/>
        <Button Width="200" Height="70" Content="按钮" FontSize="40"/>
        <TextBox Width="200" Height="100" FontSize="50">12345</TextBox>
    </UniformGrid>

二、常用控件属性

WPF中的控件属性和前端CSS比较类似,部分也可以像Winform一样进行拖拽改变(不推荐)

    <UniformGrid>
        <TextBox Width="200" Height="70" Text="文本框" FontSize="40" BorderBrush="Red" BorderThickness="2"/>
        <Border Width="200" Height="70" BorderThickness="2" BorderBrush="Blue" CornerRadius="10" Background="Gray"/>
        <Button Width="200" Height="70" Content="按钮" FontSize="40"/>
        <CheckBox Width="200" Height="70" IsChecked="True" BorderBrush="Green" BorderThickness="2"/>
        <ComboBox Width="200" Height="70"/>
        <DataGrid Width="200" Height="70"/>
        <Image Width="200" Height="70" Source="./images/1.jpg" Stretch="Fill"/>
        <Label Width="200" Height="70" Content="Label" FontSize="40" BorderBrush="Red" BorderThickness="2"/>
        <ListBox Width="200" Height="70"/>
        <RadioButton Width="200" Height="70" BorderBrush="Orange" BorderThickness="2"/>
        <TabControl Width="200" Height="70"/>
        <TextBlock Width="200" Height="70" Text="TextBlock"/>
    </UniformGrid>

1.Button(按钮控件)

1.Content(内容输入)
2.Margin(外边框与页面边框的距离)
3.Padding(内部元素与页面边框的距离)

4.Command 和 CommandParameter:用于绑定按钮的命令和参数。
5.Click:按钮点击事件的处理程序。

2.TextBox(文本框)

1.lineup()向上一行
2.selectionstart(选中文本的开始位置)
3.selectionlength(选中字符的数量)
4.selectedtext(选中的文本,可以改变change的事件)

5.MaxLength:限制输入的最大字符数。
6.TextChanged:文本框内容改变时触发的事件

3.Label (标签) 

Content:指定标签显示的文本内容。
HorizontalAlignment 和 VerticalAlignment:指定标签的水平和垂直对齐方式。 

4.Checkbox(勾选控件)

1.IsChecked(是否勾选)
2.IsthreeState(三种状态是否出现)

5.RadioButton (单选按钮) :

Content:指定单选按钮显示的文本内容。
IsChecked:指定单选按钮是否被选中。
GroupName:用于将多个单选按钮分组。

6.Text(字体)

1.fontfamily(例如宋体,楷体各种字体的集合)
2.fontsize(大小)
3.fontstyle(例斜体,倾斜)
4.fontweight(粗细)
5.fontstrech(字体拉伸属性)
6.TextDecorations="underline "(underline 下划线,overline上划线,删除线)

7.ComboBox (组合框) 

ItemsSource:指定组合框中的数据源。
SelectedItem:指定当前选中的项。
SelectionChanged:选中项改变时触发的事件。

8.ListBox (列表框) 

ItemsSource:指定列表框中的数据源。
SelectedItem:指定当前选中的项。
SelectionMode:指定选择模式,如单选、多选等。

9.Scrollviewer(滚动条)

1.Vertical(Horizontal)ScrollBarVisIbility(是否出现滚动条)
2.CanContentScroll(逐元素展示)

10.Expander(下拉菜单)

1.ExpandDirection(下拉方向)

11.Slider(滑动条)

1.Orientation="Horizontal"(显示方向)
2. Maximum=" 100"(最大值)
3. Minimum=" 0" (最小值)
4.Value=" 10" (当前数值)
5.TickPlacement="BottomRight" (可视化数值) 
6.issnaptotickenabled=“true”(移动范围只能是整数) 

12.Datapicker(日期控件)

1.IsDropDownOpen(下拉窗口是否打开)

13.Rectangle(矩形)

1.RadiusX(X轴形状变化)
2.RadiusY(X轴形状变化)
3.Stroke(边框颜色选择)

14.Ellipse(椭圆)

1.Fill(内部充满颜色)
2.Stroke(边框颜色选择)
3.Stretch(形状改变)

15.Line(直线)

1.Stroke(边框颜色选择)
2.X1(左边起点X坐标)
3.X2(右边终点X坐标)
4.Y1(左边起点Y坐标)
5.Y2(右边终点Y坐标)

16.PolyLine(折线)

1.Stroke(边框颜色选择)
2.Points(X,Y两个数定一个方向)

17.PolyGon(多边形)

1.Fill(内部充满颜色)
2.Points(X,Y两个数定一个方向)

18.ProgressBar

进度条,不可操作

1. IsIndeterminate="True"(滑动钮一直滑动)
2. Maximum=" 100"(最大值)
3. Minimum=" 0" (最小值)

19.PropertyGridControl

属性面板

1. [CategoryAttribute("基本")]( 属性分组)
2. [DisplayName("名称")]( 修改名字 )
3. [TypeConverterAttribute(ExpandableObjectConverter:: typeid)](添加 子节点 )

20.TreeView(树列) 

1.TreeViewItem Header="设备"(子元素) 

2.ItemsSource:指定树状视图的数据源。
3.SelectedItem:指定当前选中的树节点。
4.SelectedItemChanged:选中项改变时触发的事件。

21.DataGrid

AutoGenerateColumns="False"自动生成列,获取或设置一个值列是否自动创建。
在ture的情况下查出多少数据就会显示多少,而不是你设定好显示的数据。
CanUserResizeColumns="False"用户可以调整列的大小,是否可调整表格的列宽
CanUserResizeRows="False"用户可以调整行的大小,是否能更改表格的行的高度
CanUserReorderColumns="False"用户可以重新排序列
CanUserAddRows="False"用户可以添加行 

ItemsSource:指定数据网格的数据源。
Columns:指定数据网格的列定义。

22.ProgressBar (进度条) 

Value:获取或设置进度条的当前值。
Minimum Maximum:指定进度条的最小和最大值。

23.DatePicker (日期选择器) 

SelectedDate:获取或设置选择的日期。
DisplayDateStart DisplayDateEnd:指定可见的日期范围。

24.TabControl (选项卡控件) 

ItemsSource:指定选项卡的数据源。
SelectedIndex SelectedItem:指定当前选中的选项卡。
SelectionChanged:选项卡改变时触发的事件。

25.Menu (菜单栏) :

ItemsSource:指定菜单项的数据源。
Click:菜单项点击事件的处理程序。

26.WebBrowser (网页浏览器) 

Source:指定要加载的网页地址。
Navigated:网页导航完成时触发的事件。

27.RichTextBox (富文本框) 

Document:指定富文本框中的文档内容。
Selection:获取或设置当前选定的文本。

28.Expander (可展开面板) 

Header:指定面板的标题。
Content:指定在展开时显示的内容。
IsExpanded:指定面板是否展开。

29.PasswordBox (密码框) 

Password:获取或设置密码框中的密码。

30.ScrollBar (滚动条) 

Value:获取或设置滚动条的当前值。
Minimum Maximum:指定滚动条的最小和最大值。
Scroll:滚动条滚动时触发的事件。

31.MediaElement (媒体元素) 

Source:指定要播放的媒体文件路径或 URL。
Play Pause:控制媒体的播放和暂停。

32.窗口常用属性

Icon="Images/Icon/log.png"      定义任务栏图标,窗口图标 
WindowStartupLocation="CenterScreen" 窗口弹出位置。

CenterScreen屏幕中心,CenterOwner在父级窗口显示,Manual自定义显示位置,搭配Left和Top属性设置。

MinHeightMinWidth:高宽最小值。

MaxHeightMaxWidth:高宽最大值。
BorderThickness:窗口边框厚度,取消默认窗口样式,为窗口边缘设置厚度使其拥有线条
Loaded="Window_Loaded"   窗口加载事件,在窗口弹出时执行的事件,多用于主页面数据绑定,或者序列化菜单的开局加载


Title    标题    
ResizeMode    调节窗口模式    NoResize:不可调节窗口,无最大化和最小化、CanMinimize:不可调节窗口,无最大化,有最小化、CanResize:可调节窗口,有最大化,有最小化【默认】、CanResizeWithGrip:可调节窗口,有最大化,有最小化,右下角带有调节标志


WindowStyle    窗口风格    

None:不显示顶部标题栏、

SingleBorderWindow:单边框显示【默认】、

ThreeDBorderWindow:3D边框显示、

ToolWindow:工具箱窗口


ShowInTaskbar    窗口是否在任务栏中显示    true or false
WindowState    窗口默认启动状态    默认、最大化、最小化
Topmost    窗口顶层显示    ture or false

33.通用属性 

属性名称    说明    备注
Name    控件名称    
Width    控件宽度    
Height    控件高度    
HorizontalAlignment    水平对齐方式    Left:左对齐

Orientation   指定子元素排列的方向,可以是水平 (Horizontal) 或垂直 (Vertical)。
VerticalAlignment    垂直对齐方式    Left:左对齐
HorizontalContentAlignment    内容水平对齐方式    Left:左对齐
VerticalContentAlignment    内容垂直对齐方式    Left:左对齐
Margin    控件外边距    左,上,右,下
Padding    控件内边距    左,上,右,下
Foreground    前景色    
Background    背景色    
BorderThickness    边框粗细    
BorderBrush    边框颜色    
FontFamily    字体类型    Microsoft YaHei:微软雅黑
FontSize    字体大小    
FontStyle    字体风格    Italic:斜体
FontWeight    字体粗细    Bold:粗体
Opacity    控件透明度    取值:0.0~1.0
Panel.ZIndex    控件顶层显示    数值越大可遮挡其他控件
Visibility    控件可见性    Visible:显示控件、Hidden:隐藏但保留位置空间、

Collapsed:隐藏不保留位置空间

三、控件结构

1 ContentControl类

例如
<Button Content="haha" />  

<Label Content="haha" />

<CheckBox Content="haha" />
控件当前目录下只允许有一个Content,如下所示错误
<Button>
    <Image/>
    <Label/>
</Button>
要添加多个Content时需要用一个容器进行包裹,如下所示
<Button>
    <StackPanel>
        <Image/>
        <Label/>
    </StackPanel>
</Button>

2 HeaderedContentControl类

相对于ContentControl来说这类控件既可设置Content, 又可以设置带标题的Header。
像比较常见的分组控件GroupBox、TabControl子元素TabItem、它们都是具备标题和内容的控件。
<GroupBox Header="这个是GroupBox的header">
       <TextBlock/>
</GroupBox>
<TabControl Grid.Column="1">
        <TabItem Header="测试1"/>
        <TabItem Header="测试1"/>
</TabControl>
同样,该类控件目录下只允许设置一次Conent和Header, 如下错误所示, 出现2次设置Header与Content报错:
<GroupBox Header="test">--
     <GroupBox.Header>--重复
            <TextBlock/>
     </GroupBox.Header>
     <TextBlock/>
     <TextBlock/>--重复
</GroupBox>

3 ItemsControl类

此类控件大多数属于显示列表类的数据、设置数据源的方式一般通过 ItemSource 设置。如下所示:
<TabControl ItemsSource="" />
<Menu ItemsSource="" />
<ListBox ItemsSource="" />
<ItemsControl ItemsSource=""/>

4 常用控件

TextBlock: 用于显示文本, 不允许编辑的静态文本。 Text="" 设置显示文本的内容。

ComboBox: 下拉框控件, ItemSource设置下拉列表的数据源, 也可以显示设置, 如下
<ComboBox>
      <TextBlock Text="1"/>
      <TextBlock Text="2"/>
      <TextBlock Text="3"/>
</ComboBox>

四、样式

 样式的引用 类似于CSS 行内样式 和内部样式

<Window.Resources> --相当于行内样式
        <Style x:Key="style1" TargetType="Button">  
            <Setter Property="FontSize" Value="30" />
            <Setter Property="Width" Value="60" />
        </Style>
</Window.Resources>
x:Key="" :该样式的关键名称 引用该样式的时候会使用到
TargetType=""  :类型 Button/TextBox 等等控件类型
Property="" :  填入属性名称 
Value=""  :  属性对应的值

1、引用方式一

静态绑定引用
<Button Style="{StaticResource style1}" Content="test"/>
Style="{资源类型 样式名称}"

2、引用方式二

继承绑定引用
    <Window.Resources>
        <Style x:Key="baseStyle" TargetType="Button"> --声明父样式
            <Setter Property="FontSize" Value="30" />
        </Style>
        <Style x:Key="ButtonStyle" TargetType="Button"

                    BasedOn="{StaticResource baseStyle}">--继承样式
            <Setter Property="Foreground" Value="Red" />
        </Style>
    </Window.Resources>
<Button Style="{StaticResource ButtonStyle}" Content="test"/>


BasedOn="{资源类型 父样式名称}"

 3、资源类型

StaticResource      静态资源 不允许后台修改属性
DynamicResource 动态资源 允许后台修改属性

 4、样式种类

FontFamily="" 字体 默认是Microsoft YaHei
FontSize="" 字体大小
Background="" 背景颜色
Foreground=""  字体颜色
Margin="" 边距
BorderBrush=""  边框颜色;
BorderThickness=""  边框厚度
HorizontalAlignment="" 水平位置
VerticalAlignment=""  垂直位置
ShowGridLines=""  显示网格(布局)线条
FontWeight=""   字体粗细
MaxLength=""文本最大长度,用于TextBox的属性设置

SelectionChanged="ListViewMenu_SelectionChanged"绑定选择改变时运行事件,多用于主页面菜单等自定义控件

五、触发器

1、单条件触发器

<Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True"> --Property="" 填入行为
                    <Setter Property="Foreground" Value="black"/> --改变属性值
                </Trigger>
</Style.Triggers>
例:
<Style x:Key="ButtonStyle" TargetType="Button">
            <Setter Property="Foreground" Value="Red" />
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="black"/>
                </Trigger>
                <Trigger Property="IsMouseOver" Value="False">
                    <Setter Property="Foreground" Value="Blue"/>
                </Trigger>
            </Style.Triggers>
</Style>

2、多条件触发器

<MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="行为1" Value="true"/>
                        <Condition Property="行为2" Value="true" />
                    </MultiTrigger.Conditions> --行为都满足后会执行下面的属性修改
                    <MultiTrigger.Setters>
                        <Setter Property="Foreground" Value="Black"/>
                    </MultiTrigger.Setters>
</MultiTrigger>

例:
<Style x:Key="ButtonStyle" TargetType="Button" BasedOn="{StaticResource baseStyle}">
            <Setter Property="Foreground" Value="Red" />
            <Style.Triggers>
                <MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="IsMouseOver" Value="true"/>
                        <Condition Property="IsFocused" Value="true" />
                    </MultiTrigger.Conditions>
                    <MultiTrigger.Setters>
                        <Setter Property="Foreground" Value="Black"/>
                    </MultiTrigger.Setters>
                </MultiTrigger>
            </Style.Triggers>
</Style>

3、事件触发器

<EventTrigger RoutedEvent="事件类型">
                    <EventTrigger.Actions>
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation Duration="0:0:0.2"
                                                 Storyboard.TargetProperty="FontSize" --修改的属性名
                                                 To="50"> --修改后的值
                                </DoubleAnimation>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger.Actions>
</EventTrigger>
例子:
<Style x:Key="ButtonStyle" TargetType="Button" BasedOn="{StaticResource baseStyle}">
            <Setter Property="Foreground" Value="Red" />
            <Style.Triggers>
                <EventTrigger RoutedEvent="Mouse.MouseEnter">--鼠标移入事件
                    <EventTrigger.Actions>
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation Duration="0:0:0.2"
                                                 Storyboard.TargetProperty="FontSize"
                                                 To="50">
                                </DoubleAnimation>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger.Actions>
                </EventTrigger>
                <EventTrigger RoutedEvent="Mouse.MouseLeave"> --鼠标离开事件
                    <EventTrigger.Actions>
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation Duration="0:0:0.2"
                                                 Storyboard.TargetProperty="FontSize"
                                                 To="20">
                                </DoubleAnimation>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger.Actions>
                </EventTrigger>
            </Style.Triggers>
        </Style>

4、DataTrigger

5、MultiDataTrigger

六、控件模板

控件模板定义格式

 <ControlTemplate x:Key="定义名称" TargetType="控件名">
            <Border Background="Aqua" CornerRadius="5"> --天蓝色圆角
                <StackPanel Orientation="Horizontal" HorizontalAlignment="{TemplateBinding HorizontalAlignment}">--使用TemplateBinding
                    <TextBlock Text="❥" VerticalAlignment="Center"/>
                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
                                      VerticalAlignment="{TemplateBinding VerticalAlignment}"/>
                </StackPanel>
            </Border>
        </ControlTemplate>

使用模板

 <Button Template="{资源类型 模板名称}"/>
例子:按钮模板

<Window.Resources>
        <ControlTemplate x:Key="按钮模板1" TargetType="Button">
            <Border Background="Aqua" CornerRadius="5">
                <StackPanel Orientation="Horizontal" HorizontalAlignment="{TemplateBinding HorizontalAlignment}">
                    <TextBlock Text="❥" VerticalAlignment="Center"/>
                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
                                      VerticalAlignment="{TemplateBinding VerticalAlignment}"/>
                </StackPanel>
            </Border>
        </ControlTemplate>
</Window.Resources>
<Grid>
        <Button Content="haha" Width="120" Height="60" Foreground="Red"
                FontSize="30" Background="Green" VerticalAlignment="Center"
                HorizontalAlignment="Center" Template="{StaticResource 按钮模板1}"/>
</Grid>

七、数据模板

控件模板定义格式

 <ControlTemplate x:Key="定义名称" TargetType="控件名">
            <Border Background="Aqua" CornerRadius="5"> --天蓝色圆角
                <StackPanel Orientation="Horizontal" HorizontalAlignment="{TemplateBinding HorizontalAlignment}">--使用TemplateBinding
                    <TextBlock Text="❥" VerticalAlignment="Center"/>
                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
                                      VerticalAlignment="{TemplateBinding VerticalAlignment}"/>
                </StackPanel>
            </Border>
        </ControlTemplate>

使用模板
 <Button Template="{资源类型 模板名称}"/>
例子:按钮模板

<Window.Resources>
        <ControlTemplate x:Key="按钮模板1" TargetType="Button">
            <Border Background="Aqua" CornerRadius="5">
                <StackPanel Orientation="Horizontal" HorizontalAlignment="{TemplateBinding HorizontalAlignment}">
                    <TextBlock Text="❥" VerticalAlignment="Center"/>
                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
                                      VerticalAlignment="{TemplateBinding VerticalAlignment}"/>
                </StackPanel>
            </Border>
        </ControlTemplate>
</Window.Resources>
<Grid>
        <Button Content="haha" Width="120" Height="60" Foreground="Red"
                FontSize="30" Background="Green" VerticalAlignment="Center"
                HorizontalAlignment="Center" Template="{StaticResource 按钮模板1}"/>
</Grid>

八、数据绑定

元素绑定

        <StackPanel>
            <Slider x:Name="sld" Width="200" Height="60"/>
            <TextBox Height="50" Width="200" FontSize="20" Text="{Binding ElementName=sld,Path=Value,Mode=TowWay}"/>
        </StackPanel>

属性Model:
Model=Default  默认或者不写是双向绑定
Model=OneTime 一次性绑定 绑定对象只会随着被绑定数据变化 反过来不会
Model=OneWay 单向绑定
Model=OneWayToSource
Model=TowWay 双向绑定 任意一边发生变化另一边也会变

资源绑定

<Window.Resources>
        <TextBox x:Key="txt" Text="hahahahaha"/>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding Source={StaticResource txt},Path=Text}"/>  
        </StackPanel>
    </Grid>

Path=元素的值的位置 如此例中数据存在TextBox的Text中

属性绑定

XAML代码:
<TextBox x:Name="tb" Text="{Binding Name}"/>
CS代码:
tb.DataContext = new Person() { Name = "AAA" };
属性必须是public
Binding后面跟的数据名要和后端属性名对应

当前窗口数据上下文ViewModel单向绑定

XAML:
<TextBox Text="{Binding Name}"/>
CS:
this.DataContext = new ViewModelOneWay();
CS-ViewModel.Class

 public class ViewModelOneWay
    {
        public string Name { get; set; }
        public ViewModelOneWay()
        {
            Name = "Tom";
        }
    }

当前窗口上下文ViewModel双向绑定
 

CS-ViewModel.Class

class ViewModelTowWay : INotifyPropertyChanged  --必须实现该接口
    {
        public ViewModelTowWay()
        {
            Name = "张三";
            Task.Run(async () =>
            {
                await Task.Delay(3000);
                Name = "李四";
            });
        }
        public event PropertyChangedEventHandler PropertyChanged; --实现接口中的方法
        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                OnPropertyChanged("Name");//调用通知更新
            }
        }
        protected void OnPropertyChanged(string changedValue)
        {
            if (PropertyChanged != null)//当属性值改变触发事件
            {
                PropertyChangedEventArgs ee = new PropertyChangedEventArgs(changedValue);
                PropertyChanged(this, ee);//
            }
        }
    }

Nuget引用MvvmLight框架

XAML:
        <StackPanel>
            <TextBox Text="{Binding Name}"/>
            <Button Height="50" Width="80" Content="改变" FontSize="30" Command="{Binding SaveCommand}"/>
            //此处按钮绑定事件  Command="{Binding 后台Command名}
        </StackPanel>
CS:
this.DataContext = new ViewModelTowWay();

CS-ModelViewModel: 

//继承MvvmLight的ViewModelBase
class ViewModelTowWay : ViewModelBase  
  {
        public ViewModelTowWay()
        {
            Name = "张三";
            SaveCommand = new RelayCommand(() =>{ Name = "王五";});
        }
        private string name;
        public string Name
        {
            get { return name; }
            set 
            { 
                name = value;
                //此处不需要放属性名 框架已封装
                RaisePropertyChanged();
            }
        }
        //向UI暴露方法 UI进行绑定
        public RelayCommand SaveCommand { get; private set; } 
}

九、模板绑定

模板示例

文档大纲->选中控件-> 编辑模板->编辑副本  此时得到该控件的基本模板信息 
不同的控件内容呈现都是以 Presenter结尾
ContentPresenter用于呈现内容content="asdasd"

<Window.Resources>
        <Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}"                                                                     SnapsToDevicePixels="true">
                            <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}"                                                                    RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding                                                                    VerticalContentAlignment}"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsDefaulted" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>

深入学习

一、控件结构

二、资源引用

image引用资源

<Image Source="/Images/user.jpg">
  <Image.Clip>  对图片进行裁剪
     <EllipseGeometry Center="12.5,12.5" RadiusX="12.5" RadiusY="12.5" /> 裁剪为圆形
  </Image.Clip>
</Image>

三、数据、命令绑定

1.绑定数据

<TextBox  Text="{Binding OrderQTY}"/>

2.绑定命令

<Button Command="{Binding SubmtCommand}"/>

3.嵌入到DataGrid中Button绑定命令并且带一个参数

<Button Content="修改" CommandParameter="{Binding id}"
Command="{Binding DataContext.EditCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"/>

4.DataGrid绑定数据

<DataGrid ItemsSource="{Binding OrderModelList}" />

5.DataGridTextColumn绑定数据

<DataGridTextColumn Header="XX"  Binding="{Binding menuModel.Name}"/>

6.嵌入DataGrid中的CheckBox绑定属性是否选中并且绑定命令

<CheckBox IsChecked="{Binding Path=IsSelected, UpdateSourceTrigger=PropertyChanged}" 
   Command="{Binding DataContext.AddCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"/>

四、MVVM框架使用

1、MVVMLight使用

2、Prism使用

Neuget安装Prism.DryIoc 

A 手动配置Prism:

1 在App.xaml文件中引入Prism如下图所示1变更为2

 2 App.xaml.cs文件中引用Prism,重写CreateShell 和 RegisterTypes方法

3 创建主窗体内容

 

<Window x:Class="WPF_PrismNew.Views.MainView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_PrismNew"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        mc:Ignorable="d"
        Title="MainView" Height="280" Width="500">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="0.2*"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Border BorderBrush="Black" BorderThickness="1">
            <StackPanel>
                <Button Height="50" Content="模块A" Command="{Binding OpenCommand}" CommandParameter="ViewA"/>
                <Button Height="50" Content="模块B" Command="{Binding OpenCommand}" CommandParameter="ViewB"/>
                <Button Height="50" Content="模块C" Command="{Binding OpenCommand}" CommandParameter="ViewC"/>
            </StackPanel>
        </Border>
        <Border Grid.Column="1" BorderBrush="Gray" BorderThickness="1">
            <ContentControl prism:RegionManager.RegionName="ContentRegion">
                
            </ContentControl>
        </Border>
    </Grid>
</Window>

效果如下所示为一个简易demo,使用Prism 区域导航功能实现页面模块切换

添加三个View,和MainViewModel类,如下所示

 在App.xaml中重写RegisterTypes方法注册三个View

MainViewModel构造函数中注入IRegionManager,调用区域跳转方法

如上就是简单使用Prism实现页面切换。

扩展知识

一、WPF装饰器Adorner

二、WPF转换器

三、WPF行为Behavior

四、WPF动画Animation

五、WPF关键帧动画

六、验证器ValidationRule

七、WPF图表LiveChart

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值