• 02-WPF_基础(二)


    3、控件学习

    控件学习

    布局控件: panel、Grid

    内容空间:Context  之恶能容纳一个控件或布局控件

    代表提内容控件:内容控件可以设置标题  Header  父类:HeaderContextControl。

    条目控件:可以显示一列数据,数据类型一般相同:ItemControl

    带标题的条目控件:条目控件可以设置标题  Header  父类:  HeaderItemControl。

    特殊内容控件:常用的控件:TextBox  PasswordBox  TextBlock Image等。

    WPF第三方控件:

    3.1、内容控件:Content

    WPF第三方控件:

    1、Window的属性

    Window:为内容空间。

    Grid为Window窗体控件的content,,,只能有一个,Grid为布局控件.

    可以在Window控件设置ShowInTaskBar效果如下图:在任务栏有图标.

    ShowInTaskBar  是否有任务栏

    WindowState=状态:指示最大化或者最小化或者正常尺寸

    WindowStartupLocation:  启动后首次出现的位置

    Topmost:  显示在最上层

    Icon:  设置图标

    Loaded:  加载事件,页面加载数据或者控件,在MainWindow.xaml.cs里边创建函数

    1. private void Window_Loaded(object sender, RoutedEventArgs e)
    2. {
    3. RadioButton rbtn =new RadioButton();
    4. rbtn.Content = "主任";
    5. rbtn.GroupName = "role";
    6. grid.Children.Add(rbtn);
    7. rbtn.IsChecked = false;
    8. rbtn.HorizontalAlignment = HorizontalAlignment.Left;
    9. rbtn.VerticalAlignment = VerticalAlignment.Top;
    10. rbtn.Margin = new Thickness(500, 237, 0, 0);
    11. //this.grid.Children.Add(rbtn);
    12. }

    Closing

    MoseDoubleClick:

    MouseLeftButtonDown

    MouseLeftButtonUp

    MouseLeftButtonUp

    MouseRightButtonDown

    1. <Window x:Class="_01WPF基础.MainWindow"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    6. xmlns:local="clr-namespace:_01WPF基础"
    7. mc:Ignorable="d"
    8. Title="MainWindow" Height="450" Width="800" WindowStartupLocation="CenterScreen" WindowState="Normal" Topmost="True"
    9. Icon="image/12window.png" Loaded="Window_Loaded">

    上述为Window的属性

    3.2、标签文本框内容控件

    Label  文本标签 contextControl

    TextBox  特殊内容

    PasswordBox

    WPF允许空间没名称,但是引用时候需要命名

    1. <Window x:Class="_01WPF基础.MainWindow"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    6. xmlns:local="clr-namespace:_01WPF基础"
    7. mc:Ignorable="d"
    8. Title="MainWindow" Height="450" Width="800" WindowStartupLocation="CenterScreen" WindowState="Normal" Topmost="True"
    9. Icon="image/12window.png" Loaded="Window_Loaded">
    10. <Grid>
    11. <Grid.ColumnDefinitions>
    12. <ColumnDefinition/>
    13. <ColumnDefinition/>
    14. Grid.ColumnDefinitions>
    15. <StackPanel Grid.ColumnSpan="2" Margin="0,10,533,-10">
    16. <TextBlock x:Name="tbName" HorizontalAlignment="Left" Margin="20,60,0,0" TextWrapping="Wrap" Text="{Binding Value,UpdateSourceTrigger=PropertyChanged}" Height="25" RenderTransformOrigin="0.5,0.5" Width="76"
    17. Foreground="{Binding ValueColor}"/>
    18. <Label x:Name="用户名" Content="登录" HorizontalAlignment="Left" Margin="20,80,0,0" Width="46" RenderTransformOrigin="0.476,-0.105" />
    19. <Button Content="Button" HorizontalAlignment="Left" Margin="22,80,0,0" Command="{Binding ValueCommand}"
    20. CommandParameter="123" RenderTransformOrigin="0.197,0.579"/>
    21. <Button HorizontalAlignment="Left" Margin="22,42,0,0" VerticalAlignment="Top" Command="{Binding ValueCommand}"
    22. CommandParameter="123" RenderTransformOrigin="0.197,0.579">
    23. Buttonr1
    24. Button>
    25. StackPanel>
    26. <ItemsControl Grid.Column="1" ItemsSource="{Binding ValueList}" Background="LightGray" HorizontalAlignment="Right" Width="400">
    27. <ItemsControl.ItemTemplate>
    28. <DataTemplate>
    29. <StackPanel Orientation="Horizontal">
    30. <TextBlock Text="{Binding Value}">TextBlock>
    31. <TextBlock Text="{Binding Name}">TextBlock>
    32. StackPanel>
    33. DataTemplate>
    34. ItemsControl.ItemTemplate>
    35. ItemsControl>
    36. Grid>
    37. Window>

    1、Button按钮

    Button的属性

    BorderBrush:  背景颜色 ,例如:BorderBrush="Red"   

    BorderThickness: 背景厚度 ,例如 BorderThickness=“1”

    Foreground:  字体颜色

    HorizontalAlignment:  水平对齐

    fontStretch:字体拉伸

    Button.BackGround:背景色或者图片

    Foreground: 前景色, 文本字体,大小

    IsDefault="true":敲击Enter触发

    IsCancel="true":  敲击Enter触发

    按钮背景图片

    1. <Button HorizontalAlignment="Left" Margin="22,42,0,0" VerticalAlignment="Top" Command="{Binding ValueCommand}"
    2. CommandParameter="123" RenderTransformOrigin="0.197,0.579">
    3. <Button.Background>
    4. <ImageBrush ImageSource="image/12window.png">ImageBrush>
    5. Button.Background>
    6. Button>

    2、MessageBox

    消息框

    按钮事件显示框

    3、RadioButton

    GroupBox:互斥

    属性

    GroupName="role"     组名命名相同则互斥,设置一个组名不同组名,它们不具备互斥的关系。

    点击RadioButton触发Checked事件则传入的是一个对象Object这个是传入的控件本身:

    1. private void RadioButton_Checked(object sender, RoutedEventArgs e)
    2. {
    3. MessageBox.Show((sender as RadioButton).Content.ToString());
    4. }
    1. <Grid>
    2. <Button Name="btnLogin" Content="登录" HorizontalAlignment="Left" Margin="179,276,0,129" Width="60" Height="30">
    3. <Button.Background>
    4. <ImageBrush ImageSource="image/12window.png">ImageBrush>
    5. Button.Background>
    6. Button>
    7. <TextBox Name="txtUName" HorizontalAlignment="Left" Margin="209,166,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
    8. <Label Content="账户" HorizontalAlignment="Left" Margin="144,166,0,0" VerticalAlignment="Top"/>
    9. <Label Content="密码" HorizontalAlignment="Left" Margin="147,0,0,0" VerticalAlignment="Center"/>
    10. <Button Name="BtnCancel" Content="取消" HorizontalAlignment="Left" Margin="288,276,0,0" VerticalAlignment="Top" Click="BtnCancel_Click" Width="60" Height="30"/>
    11. <PasswordBox Name="txtUPwd" HorizontalAlignment="Left" Margin="211,205,0,0" Password="123456" PasswordChar="*" VerticalAlignment="Top" Width="120"/>
    12. <RadioButton Content="管理员" HorizontalAlignment="Left" GroupName="role" Margin="147,242,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked"/>
    13. <RadioButton Content="教师" HorizontalAlignment="Left" GroupName="role" Margin="288,242,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked"/>
    14. <RadioButton Content="学生" HorizontalAlignment="Left" GroupName="role" Margin="408,237,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked"/>
    15. Grid>

    4、CheckBox复选框

    复选框:允许选择多个

    常用属性: Content   Name   IsChecked(True,False,Null)    IsThreeState="True"

    事件:常见的事件有Checked   Click   UnChecked

    XAML文件程序

    1. <CheckBox Name="chkSport" Content="体育" IsChecked="False" HorizontalAlignment="Left" Margin="460,256,0,0" VerticalAlignment="Top" IsThreeState="True"/>
    2. <CheckBox Content="唱歌" IsChecked="False" HorizontalAlignment="Left" Margin="500,256,0,0" VerticalAlignment="Top" IsThreeState="True"/>
    3. <CheckBox Content="跳舞" IsChecked="False" HorizontalAlignment="Left" Margin="559,256,0,0" VerticalAlignment="Top" IsThreeState="True"/>
    4. <Button Content="获取" HorizontalAlignment="Left" Margin="504,325,0,0" VerticalAlignment="Top" Click="Button_Click"/>

    1. public partial class MainWindow : Window
    2. {
    3. public MainWindow()
    4. {
    5. InitializeComponent();
    6. }
    7. private void BtnCancel_Click(object sender, RoutedEventArgs e)
    8. {
    9. }
    10. private void RadioButton_Checked(object sender, RoutedEventArgs e)
    11. {
    12. MessageBox.Show((sender as RadioButton).Content.ToString());
    13. }
    14. private void Window_Loaded(object sender, RoutedEventArgs e)
    15. {
    16. RadioButton rbtn =new RadioButton();
    17. rbtn.Content = "主任";
    18. rbtn.GroupName = "role";
    19. grid.Children.Add(rbtn);
    20. rbtn.IsChecked = false;
    21. rbtn.HorizontalAlignment = HorizontalAlignment.Left;
    22. rbtn.VerticalAlignment = VerticalAlignment.Top;
    23. rbtn.Margin = new Thickness(500, 237, 0, 0);
    24. //this.grid.Children.Add(rbtn);
    25. }
    26. private void Button_Click(object sender, RoutedEventArgs e)
    27. {
    28. // using System.Windows.Controls; 这个命名控件允许 里的控件可以直接被索引,例如chkSport控件:CheckBox
    29. // MessageBox.Show(chkSport.IsChecked.ToString());
    30. // 获取窗口中所有勾选的CheckedBox的Content
    31. //string strContents = "";
    32. //foreach (UIElement ele in grid.Children)
    33. //{
    34. // CheckBox chb = ele as CheckBox;
    35. // if (chb is CheckBox)
    36. // {
    37. // if (chb.IsChecked == true)
    38. // {
    39. // if (strContents != "")
    40. // strContents += ",";
    41. // strContents += chb.Content.ToString();
    42. // }
    43. // }
    44. //}
    45. //MessageBox.Show(strContents);
    46. // 代码动态不回CheckBox
    47. string[] names = { "体育", "唱歌", "跳舞" };
    48. for (int i = 0; i < names.Length; i++)
    49. {
    50. CheckBox chk = new CheckBox();
    51. chk.Content = names[i];
    52. chk.HorizontalAlignment = HorizontalAlignment.Left;
    53. chk.VerticalAlignment = VerticalAlignment.Top;
    54. chk.Margin = new Thickness(40 + i * 80, 60, 0, 0);
    55. grid.Children.Add(chk);
    56. }
    57. }
    58. }

    5、Image 图像控件

    属性

    四种拉伸模式

    Stretch属性

    四种拉伸模式

    None=0,保持内容原始大小。

    Fill=1:调整内容大小以填充目标尺寸,不保留纵横比。

    Uniform=2:在保留内容原有纵横比的同时调整内容的大小,以适合目标尺寸,纵横比不够的空白。

    UniformToFill=3,在保留内容原有纵横比的同时调整内容的大小,以适合目标尺寸,如果目标的纵横比不同于源矩形的纵横比,则会对源内容进行裁剪以适合目标尺寸。

    StretchDirection

    UpOnly  =0,内容仅在小于父级时扩展。如果内容较大,则不执行缩放。

    DownOnly=1,内容仅在大于父级时缩放,如果内容较小,则不会执行任何扩展。

    Both=2,内容将根据System.Window.Media.stretch模式进行拉伸以适应父级。

    查看文件路径

    6、Border边界

    围绕其他控件周围  或者设置背景色,

    设置边框

    属性:下面三个属性分别为边框颜色,粗细,圆角大小

    BorderBrush="Black" BorderThickness="1" CornerRadius="5" 

    Padding=”5“内部元素与边框的边距

    1. <Grid>
    2. <Border BorderBrush="Black" BorderThickness="1" CornerRadius="5" HorizontalAlignment="Left" Margin="276,129,0,0" Background="Yellow"
    3. Padding="5" Width="100" Height="30" VerticalAlignment="Top">
    4. <Label Content="用户名" HorizontalContentAlignment="Center">Label>
    5. Border>
    6. Grid>

    应用与布局面板一起使用,作为任意控制的边框显示,不是布局面板

    只能有一个子元素

    多个子元素时可以结合布局面板使用

    事件:  

    7、下拉框ComboBox

    下拉框属于条目控件(ItemsControl)  下拉框绑定,,可以通过Binding方式绑定

    第一种绑定方式: 

    1. <ComboBox Name="cboClassed" HorizontalAlignment="Left" Margin="136,202,0,0" VerticalAlignment="Top"
    2. Width="190" Height="41" IsDropDownOpen="False" Grid.ColumnSpan="2">
    3. <ComboBoxItem Content="请选择">ComboBoxItem>
    4. <ComboBoxItem Content="英语版">ComboBoxItem>
    5. <ComboBoxItem Content="数学班">ComboBoxItem>
    6. <ComboBoxItem Content="软件版">ComboBoxItem>
    7. <ComboBoxItem Content="数据班">ComboBoxItem>
    8. ComboBox>

    第二种

     IsDropDownOpen="True"  下拉框在程序运行时是打开的

    1. <ComboBox HorizontalAlignment="Left" Margin="136,231,0,0" VerticalAlignment="Top"
    2. Width="190" Height="41" IsDropDownOpen="True">
    3. <ComboBoxItem Content="请选择">ComboBoxItem>
    4. <ComboBoxItem Content="英语版">ComboBoxItem>
    5. <ComboBoxItem Content="数学班">ComboBoxItem>
    6. <ComboBoxItem Content="软件版">ComboBoxItem>
    7. <ComboBoxItem Content="数据班">ComboBoxItem>
    8. ComboBox>

    代码实现:数据库连接,,想自由Add和RemoveAt方式绑定,不要绑定数据源如下:

    1. public _04ComboboxWindow()
    2. {
    3. InitializeComponent();
    4. }
    5. private void Window_Loaded(object sender, RoutedEventArgs e)
    6. {
    7. // 获取数据源
    8. List<string> list = new List<string>(); // 连接数据库的内容
    9. cboClasses.SelectedValuePath = "ClassId"; // 项的值对应的属性名
    10. cboClasses.DisplayMemberPath = "ClassName"; // 项的显示文本对应的属性名
    11. // 另一种方式,通过对list操作进行下拉框的添加和删除
    12. //cboClasses.DataContext = list;
    13. //cboClasses.ItemsSource = null;
    14. //list.Add(new ClassInfo){
    15. // CalssId = 4;
    16. // ClassName = "音乐课";
    17. //}
    18. //cboClasses.ItemsSource = list;
    19. //cboClasses.ItemsSource = list; // 指定资源
    20. }
    21. private void Button_Click(object sender, RoutedEventArgs e)
    22. {
    23. cboClassed.Items.RemoveAt(1);
    24. }
    25. }

    指定数据源不能这样操作.3不能使用 Items.RemoveAt() 函数

    1. private void Window_Loaded(object sender, RoutedEventArgs e)
    2. {
    3. // 获取数据源
    4. List<string> list = new List<string>(); // 连接数据库的内容
    5. cboClasses.SelectedValuePath = "ClassId"; // 项的值对应的属性名
    6. cboClasses.DisplayMemberPath = "ClassName"; // 项的显示文本对应的属性名
    7. cboClasses.ItemsSource = list; // 指定资源
    8. }
    9. // 指定数据源不能这样操作
    10. private void Button_Click(object sender, RoutedEventArgs e)
    11. {
    12. cboClasses.Items.RemoveAt(1);
    13. }

    如果想实现,则先对数据源操作再赋值

    第三种绑定

    主窗口程序:   DataContext  数据上下文或者数据资源

    1. // 获取数据源
    2. List<string> list = new List<string>(); // 连接数据库的内容
    3. cboClasses.SelectedValuePath = "ClassId"; // 项的值对应的属性名
    4. cboClasses.DisplayMemberPath = "ClassName"; // 项的显示文本对应的属性名
    5. // 另一种方式,通过对list操作进行下拉框的添加和删除
    6. cboClasses.DataContext = list;

    XAML:程序,ItemsSource需要绑定

    1. "cboClasses" HorizontalAlignment="Left" Margin="174,309,0,0" VerticalAlignment="Top" Width="120" Grid.ColumnSpan="2"
    2. ItemsSource="{Binding }">

    或者:

    事件:  SelectionChanged  选择改变触发

    1. <ComboBox Name="cboClassed" HorizontalAlignment="Left" Margin="136,202,0,0" VerticalAlignment="Top"
    2. Width="190" Height="41" IsDropDownOpen="False" Grid.ColumnSpan="2" SelectionChanged="cboClassed_SelectionChanged">
    3. <ComboBoxItem Content="请选择">ComboBoxItem>
    4. <ComboBoxItem Content="英语版">ComboBoxItem>
    5. <ComboBoxItem Content="数学班">ComboBoxItem>
    6. <ComboBoxItem Content="软件版">ComboBoxItem>
    7. <ComboBoxItem Content="数据班">ComboBoxItem>
    8. ComboBox>

    代码:

    1. private void cboClassed_SelectionChanged(object sender, SelectionChangedEventArgs e)
    2. {
    3. // MessageBox.Show((cboClassed.SelectedItem as ClassInfo).ClassName);
    4. MessageBox.Show(cboClassed.SelectedItem.ToString());
    5. }

    SelectionModel :  选择模式,,选择多项还是单项。

    Selection是名词还是selected这个,,一个是名词一个是被选择

    8、ListBox  列表框

    属性:IsDropDownOpen  启动后是否打开,下拉

    包含可选择的列表:: 属于条目控件  ItemsControl

    绑定方式:  

    绑定方式ComboBox类似,一样,可以添加任意数据类型的值作为项

    1. private void Window_Loaded(object sender, RoutedEventArgs e)
    2. {
    3. ltbox.ItemsSource=new List();
    4. ltbox.SelectedValuePath = "1";
    5. ltbox.DisplayMemberPath= "音乐";
    6. }
    1. <Grid>
    2. <ListBox Name="ltbox" HorizontalAlignment="Left" Margin=" 120,120,0,0" VerticalAlignment="Top" Width="160" Height="30" SelectionChanged="ltbox_SelectionChanged">
    3. <ListBoxItem Content="选择...">ListBoxItem>
    4. <ListBoxItem Content="软件">ListBoxItem>
    5. <ListBoxItem Content="数学">ListBoxItem>
    6. ListBox>
    7. Grid>

    两个列表框中的项目相互异动,不太适合ItemsSource.Items.Add(_方式添加,可与i灵活添加或删除

    事件

    SelectedChanged :  选择项类型,由绑定或添加时数据的类型决定

    9、DataPicker  日期选择控件

    控件:属于Control

    1. <DatePicker HorizontalAlignment="Left" Margin="30,60,0,0" VerticalAlignment="Top" Width="369" Height="40"
    2. DisplayDate="2020-02-01" DisplayDateStart="2020-01-01" DisplayDateEnd="2099-02-02">
    3. DatePicker>

    自定义格式:自定义Style

    1. <Grid>
    2. <DatePicker Name="dpDate" HorizontalAlignment="Left" Margin="30,60,0,0" VerticalAlignment="Top" Width="100" Height="30"
    3. DisplayDate="2020-02-01" DisplayDateStart="2020-01-01" DisplayDateEnd="2099-02-02" FirstDayOfWeek="Monday" SelectedDateFormat="Short"
    4. SelectedDateChanged="dpDate_SelectedDateChanged">
    5. <DatePicker.Resources>
    6. <Style TargetType="DatePickerTextBox">
    7. <Setter Property="BorderThickness" Value="0">Setter>
    8. <Setter Property="Template">
    9. <Setter.Value>
    10. <ControlTemplate>
    11. <TextBox x:Name="PART_TextBox" Text="{Binding Path=SelectedDate,StringFormat={}{0:yyyy-MM-dd},RelativeSource={RelativeSource
    12. AncestorType={x:Type DatePicker}}}"/>
    13. ControlTemplate>
    14. Setter.Value>
    15. Setter>
    16. Style>
    17. DatePicker.Resources>
    18. DatePicker>
    19. Grid>

    绑定:启动之后效果

    事件:  

    SelectedDateChanged:   被选的日期改变

    1. private void dpDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
    2. {
    3. MessageBox.Show(dpDate.Text);
    4. MessageBox.Show(dpDate.SelectedDate.Value.ToString());
    5. }

    10、Canlendar日历

    可以选择一个日期范围  属于: Control

    属性:  

    可以选择多个日期范围,单个日期范围,显示范围  显示模式默认为Month

    CalendarDayButtonStyle:  

    选中多个日期如何获取开始和结束日期:避免双击button才触发

    1. private void cld_Date_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
    2. {
    3. stDate.Text = cld_Date.SelectedDates.First().ToShortDateString();
    4. edDate.Text=cld_Date.SelectedDates.Last().ToShortDateString();
    5. }
    6. private void Button_Click(object sender, RoutedEventArgs e)
    7. {
    8. txtSel.Text= cld_Date.SelectedDate.Value.ToString();
    9. }
    10. private void cld_Date_PreviewMouseUp(object sender, MouseButtonEventArgs e)
    11. {
    12. if (Mouse.Captured is CalendarItem)
    13. {
    14. Mouse.Capture(null); // 选中置空
    15. }
    16. }

    CalendarItem  命名空间:  System.Windows.Controls.Primitives

    1. <Grid>
    2. <Calendar Name="cld_Date" HorizontalAlignment="Left" Margin="129,116,0,0" VerticalAlignment="Top" DisplayMode="Month" DisplayDateStart="2020-5-1" DisplayDateEnd="2999-5-1"
    3. SelectionMode="MultipleRange" IsTodayHighlighted="True" SelectedDatesChanged="cld_Date_SelectedDatesChanged" PreviewMouseUp="cld_Date_PreviewMouseUp" >
    4. Calendar>
    5. <TextBox Name="stDate" HorizontalAlignment="Left" Margin="162,68,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
    6. <TextBox Name="edDate" HorizontalAlignment="Left" Margin="400,68,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
    7. <Button Content="Button" HorizontalAlignment="Left" Margin="400,200,0,0" VerticalAlignment="Top" Click="Button_Click"/>
    8. <TextBox Name="txtSel" HorizontalAlignment="Left" Margin="578,140,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
    9. Grid>

    事件:  

    SelectedDatesChanged:    日期为复数加s

    当多选发生时候: 即SelectionMode="MultipleRange"

    如何获取开始和结束日期:

    11、slider滑块

    TickFrequency:刻度之间的间隔

    IsSnapToTickEnabled="True"

    当更改某个 Thumb 位置并 IsSnapToTickEnabled 设置为 true该属性时,会自动 Thumb 将该位置移动到最近的刻度线

    Opacity:  透明度

    Orientation:  方向;

    Binding绑定的方式

    1. <Grid>
    2. <Slider Name="Slider1" HorizontalAlignment="Left" Margin="106,132,0,0" VerticalAlignment="Top" Width="120" Maximum="100" Minimum="50" Orientation="Horizontal"
    3. TickPlacement="Both" TickFrequency="2" Height="44" IsSnapToTickEnabled="True" SmallChange="5" LargeChange="10" IsDirectionReversed="True"
    4. IsSelectionRangeEnabled="True" SelectionStart="20" SelectionEnd="50"/>
    5. <Label Content="{Binding ElementName=Slider1,Path=Value,Mode=OneWay}" HorizontalAlignment="Left" Margin="330,163,0,0" VerticalAlignment="Top"/>
    6. <TextBox Name="tb1" HorizontalAlignment="Left" Margin="166,252,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Height="27"
    7. Text="Slider1" FontSize="{Binding ElementName=Slider1,Path=Value,Mode=OneWay}" Opacity="{Binding ElementName=Slider2,Path=Value,Mode=Default}"/>
    8. <Slider Name="Slider2" HorizontalAlignment="Left" Margin="535,217,0,0" VerticalAlignment="Top" Width="120" Maximum="1" Minimum="0" Orientation="Horizontal"
    9. TickPlacement="Both" TickFrequency="0.1" Height="44" IsSnapToTickEnabled="True" SmallChange="5" LargeChange="10" IsDirectionReversed="True"
    10. IsSelectionRangeEnabled="True" SelectionStart="20" SelectionEnd="50"/>
    11. Grid>

    12、ProcessBar进度条

    属性

    IsIndeterminate:   不确定的,指示进度是显示实际值,true连续进度反馈

    命名控件,using Windows.Controls.ProgressBar;

    1. <Grid>
    2. <PasswordBox HorizontalAlignment="Left" Margin="141,286,0,0" VerticalAlignment="Top" Width="120" Password="*"/>
    3. <ProgressBar Name="pb1" HorizontalAlignment="Left" Height="10" Margin="235,177,0,0" VerticalAlignment="Top" Width="100" Orientation="Horizontal"
    4. Minimum="0" Maximum="100" SmallChange="1" ValueChanged="pb1_ValueChanged"/>
    5. <ProgressBar Name="pb2" HorizontalAlignment="Left" Height="143" Margin="563,217,0,0" VerticalAlignment="Top" Width="50" Orientation="Vertical"
    6. RenderTransformOrigin="0.5,0.5" Minimum="0" Maximum="100" Value="0" IsIndeterminate="True"/>
    7. <Button Name="bt1" Content="加载" HorizontalAlignment="Left" Margin="347,303,0,0" VerticalAlignment="Top" Click="bt1_Click"/>
    8. <Label Name="lb1" Content="Label" HorizontalAlignment="Left" Margin="261,360,0,0" VerticalAlignment="Top"/>
    9. Grid>

    代码:XAML中  pb1属性中不可设置Value属性,若要写如下代码:

    1. public _09ProcessBarWindow()
    2. {
    3. InitializeComponent();
    4. }
    5. private void bt1_Click(object sender, RoutedEventArgs e)
    6. {
    7. double max = pb1.Maximum;
    8. Task.Run(() =>
    9. {
    10. for (int i = 1; i
    11. {
    12. pb1.Dispatcher.Invoke(() =>
    13. {
    14. pb1.Value = i;
    15. //lb1.Content = pb1.Value + "%";
    16. });
    17. Thread.Sleep(100);
    18. }
    19. });
    20. }
    21. private void pb1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    22. {
    23. lb1.Content = e.NewValue ;
    24. }

    注释:

    13、StackPanel

    布局控件,类似Grid

    属性: 

    Orientation=Horizontal  一行,一般设置VerticalAligment=Top  Bottom  Center Streth

    vertical  一列,,HorizontalAligment=Left Right  Center  Streth

    子元素超出部分,被隐藏,可嵌套

    1. "Horizontal" VerticalAlignment="Top" FlowDirection="LeftToRight">

    14、WrapPanel流面板

    Orientation:子元素按照顺序排列,如果按照水平方向:从左到右,超出部分,自动换行到下一行;如果为垂直,从上到下,超出部分自动换行到下一列。

    Orientation:    ItemWidth  ItemHeight

    1. <Border BorderBrush="Red" BorderThickness="2" CornerRadius="5" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30,30,0,0" Width="300" Height="300">
    2. <WrapPanel Name="wp1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="236" Height="248" ItemHeight="30" ItemWidth="30">
    3. <Button>bt1Button>
    4. <Button>bt2Button>
    5. <Button>bt3Button>
    6. <Button>bt4Button>
    7. <Button>bt5Button>
    8. <Button>bt6Button>
    9. WrapPanel>
    10. Border>

    代码:

    1. private void Window_Loaded(object sender, RoutedEventArgs e)
    2. {
    3. for(int i = 0; i < 100; i++)
    4. {
    5. Button btn=new Button();
    6. btn.Content= "btn"+i.ToString("00")+"号";
    7. btn.Background=new SolidColorBrush(Colors.White);
    8. btn.Name ="btn"+i.ToString();
    9. btn.Margin=new Thickness(5,5,0,0);
    10. wp1.Children.Add(btn);
    11. }
    12. }

    15、DockPanel停靠面板

    停靠面板:  顶部,左边,右边,,中间,  Winform  Dock:Top, left  right,  center

    先添加的元素,有限占有权,所有子元素不会重叠,依次排列

    与其他布局控件一起使用,

    1. <Grid>
    2. <DockPanel LastChildFill="False" HorizontalAlignment="Left" Margin="0" VerticalAlignment="Top" Height="341" Width="477"
    3. >
    4. <StackPanel Width="50" Height="50" Background="LightBlue" DockPanel.Dock="Right">StackPanel>
    5. <StackPanel DockPanel.Dock="Left" Background="LightGreen" Height="30" Width="30">StackPanel>
    6. <StackPanel Width="100" Height="50" DockPanel.Dock="Left" Background="LightBlue">
    7. <Label Content="left2"/>
    8. StackPanel>
    9. <StackPanel Width="100" Height="50" DockPanel.Dock="Bottom" Background="LightBlue">
    10. <Label Content="bottom"/>
    11. StackPanel>
    12. <Grid Width="50" Height="50" Background="BlueViolet"/>
    13. <Grid Background="Orange" Width="210" Height="123">
    14. <DockPanel Margin="0,0,28,22">
    15. <Button Content="top" Height="5" DockPanel.Dock="Top">Button>
    16. <Button Content="Left" Height="5" DockPanel.Dock="Left">Button>
    17. <Button Content="Right" Height="5" DockPanel.Dock="Right">Button>
    18. <Button Content="bottom" DockPanel.Dock="Bottom" Height="10"/>
    19. DockPanel>
    20. Grid>
    21. DockPanel>
    22. Grid>

    事件:  

    16、Canvas画布

    定义区域,子元素的显示位置,指定相对于

    属性:

    不能为子元素指定两个以上的附加属性,如果制定了,忽略后者;

    当拆给你扣大小变化时,Canvas的尺寸随之变化,

    重叠效果,优先显示:后添加的元素显示在上面,Panel.ZIndex相同,后添加显示在上边。

    1. <Grid>
    2. <Canvas Margin="55,0,484,150">
    3. <Button Content="first" Width="30" Height="20" Canvas.Left="20" Canvas.Top="30" Canvas.Right="30" Canvas.Bottom="30">Button>
    4. <Button Content="second" Width="50" Height="20" Canvas.Left="30" Canvas.Bottom="30">Button>
    5. <Button Content="third" Width="30" Height="20" Canvas.Right="20" Canvas.Top="30">Button>
    6. <Button Content="fourth" Width="30" Height="20" Canvas.Right="20" Canvas.Bottom="30">Button>
    7. <Button Content="按钮1" Width="30" Height="20" Canvas.Right="20" Canvas.Top="30">Button>
    8. <Button Content="按钮2" Width="30" Height="20" Canvas.Left="50" Canvas.Top="100" RenderTransformOrigin="0.676,2.303" Panel.ZIndex="2">Button>
    9. <Button Content="按钮2" Width="30" Height="20" Canvas.Left="55" Canvas.Top="115" RenderTransformOrigin="0.676,2.303" Panel.ZIndex="1">Button>
    10. <Button Content="按钮2" Width="30" Height="20" Canvas.Left="60" Canvas.Top="130" RenderTransformOrigin="0.676,2.303" Panel.ZIndex="1">Button>
    11. Canvas>
    12. Grid>

    17、Grid网格

    网格面板,类似于WinformTableLayoutPanel,行和列布局页面或页面中某一块区域。

    单元格--一个元素或多个元素,

    容器--多个控件,StackPanel、WrapPanel、DockPanel、Grid、TabControl、GroupBox、Expander、Frame。

    元素指定的位置:指定该元素所在的行索引和列索引,从0开始,如果没有指定,默认就是第一个单元格 0 0 ,Row Column  跨行或跨列 RowSpan  Colspan

    定义Grid的行和列

    尺寸:三种,固定:30;  按照比例:1*  2*  ;auto:按照内容自动调整。

    没有设置height width,平均分配。

    Grid控件格局复杂,与DockPanel控件结合,

    1. <Grid Height="400" Width="600" ShowGridLines="True" Background="BlueViolet">
    2. <Grid.RowDefinitions>
    3. <RowDefinition Height="53">RowDefinition>
    4. <RowDefinition/>
    5. <RowDefinition Height="30">RowDefinition>
    6. <RowDefinition Height="53">RowDefinition>
    7. <RowDefinition Height="auto" MinHeight="15">RowDefinition>
    8. Grid.RowDefinitions>
    9. <Grid.ColumnDefinitions>
    10. <ColumnDefinition>ColumnDefinition>
    11. <ColumnDefinition>ColumnDefinition>
    12. <ColumnDefinition>ColumnDefinition>
    13. <ColumnDefinition>ColumnDefinition>
    14. <ColumnDefinition>ColumnDefinition>
    15. Grid.ColumnDefinitions>
    16. <TextBox Grid.Column="1">TextBox>
    17. <TextBlock Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Background="LightGray">TextBlock>
    18. <Label Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" Background="YellowGreen" Content="用户信息:">Label>
    19. <Label Grid.Row="3" Grid.Column="1" Background="YellowGreen" Content="用信息:" Margin="20,10,26,0"/>
    20. <Label Grid.Row="3" Grid.Column="1" Background="YellowGreen" Content="用信息123:" Margin="20,10,0,10">Label>
    21. <WrapPanel Grid.Column="1" Grid.Row="2" Background="SeaShell">
    22. <Button Content="bt1" Height="25" Width="40">Button>
    23. <Button Content="bt1" Height="25" Width="40">Button>
    24. <Button Content="bt1" Height="25" Width="40">Button>
    25. <Button Content="bt1" Height="25" Width="40">Button>
    26. <Button Content="bt1" Height="25" Width="40">Button>
    27. WrapPanel>
    28. Grid>

    把Grid中的Height="400" Width="600"去掉,就可以自动方所。

    18、GroupBox组框

    分组容器控件:继承HeaderedContentControl,命名空间Control控件

    分组,带标题,HeaderedContentControl带标题的内容空间

    只有一个子元素作为它的内容  Content  

    属性::

    循环嵌入:

    1. <Grid>
    2. <GroupBox Header="=导航菜单" Width="200" Height="200" Margin="0,0,552,218">
    3. <StackPanel Orientation="Horizontal">
    4. <Label Content="用户1">Label>
    5. <Label Content="用户2">Label>
    6. <Label Content="用户3">Label>
    7. <Label Content="用户4">Label>
    8. <Label Content="用户5">Label>
    9. StackPanel>
    10. GroupBox>
    11. <GroupBox Header="=导航菜单2" Width="200" Height="200" Margin="300,31,300,204">
    12. <StackPanel Orientation="Vertical">
    13. <StackPanel Orientation="Horizontal">
    14. <Label Content="用户">Label>
    15. <TextBox Text="123456">TextBox>
    16. StackPanel>
    17. <StackPanel Orientation="Horizontal">
    18. <Label Content="用户">Label>
    19. <TextBox Text="123456">TextBox>
    20. StackPanel>
    21. StackPanel>
    22. GroupBox>
    23. Grid>
    1. public partial class _14GroupBoxWindow : Window
    2. {
    3. public _14GroupBoxWindow()
    4. {
    5. InitializeComponent();
    6. }
    7. private void Window_Loaded(object sender, RoutedEventArgs e)
    8. {
    9. StackPanel spFirst = gp2.Content as StackPanel; // 为何内容为StackPanel
    10. foreach(var ele in spFirst.Children)
    11. {
    12. StackPanel sp = ele as StackPanel;
    13. foreach(var ele2 in sp.Children)
    14. {
    15. if(ele2 is TextBox)
    16. {
    17. TextBox tet = ele2 as TextBox;
    18. string name = txtUserName.Text;
    19. }
    20. }
    21. }
    22. string name2= txtUserName.Text; // 直接通过name属性获取控件的Text
    23. }
    24. }

    事件::

    19、Expander扩展折叠控件

    折叠控件,GroupBox  带标题,HeaderedContentControl

    折叠或展开的特点,IsExpand 是否复合显示内容,ExpandDirection展开方向  Down Top/Left/Right。

    GroupBox  不能折叠内容部分,Expander可以折叠,节省区域。

    1. <Grid Margin="0,0,433,167">
    2. <Expander>
    3. <Grid RenderTransformOrigin="0.626,0.502">
    4. <Grid.ColumnDefinitions>
    5. <ColumnDefinition>ColumnDefinition>
    6. <ColumnDefinition>ColumnDefinition>
    7. Grid.ColumnDefinitions>
    8. Grid>
    9. Expander>
    10. <Expander Header="用户权限" HorizontalAlignment="Left" Height="165" Margin="110,91,0,0" VerticalAlignment="Top" Width="auto"
    11. Padding="10" ExpandDirection="Up" BorderThickness="2" RenderTransformOrigin="0.5,0.5" IsExpanded="False">
    12. <Expander.RenderTransform>
    13. <TransformGroup>
    14. <ScaleTransform/>
    15. <SkewTransform AngleX="-0.576"/>
    16. <RotateTransform/>
    17. <TranslateTransform X="0.829"/>
    18. TransformGroup>
    19. Expander.RenderTransform>
    20. <StackPanel Background="#FFE5E5E5">
    21. <CheckBox Content="管理员">CheckBox>
    22. <CheckBox Content="系统管理员">CheckBox>
    23. StackPanel>
    24. Expander>
    25. Grid>

    20、TabControl选项卡控件

    组件:多个共享相同的空间。

    Selector  ItemsControl:条目控件:ListBox,   ComboBox:下拉框。

    SelectedValue:SelectedItem、SelectedValuePath、Display

    TabItem: 里边只能有一个StackPanel  不能有俩

    选项卡项:TabItem---HeaderedContentControl  Header。

    SelectedContent    Selected Item:TabItem对象。

    TabItem:  IsSelected  设置或者获取当前显示界面

    1. <Grid>
    2. <TabControl Name="tabCl" HorizontalAlignment="Left" Height="244" Margin="141,90,0,0" VerticalAlignment="Top" Width="398"
    3. TabStripPlacement="Top">
    4. <TabItem Header="用户信息" IsSelected="True">
    5. <StackPanel Orientation="Vertical" Background="YellowGreen">
    6. <StackPanel Orientation="Horizontal">
    7. <Label Content="用户名">Label>
    8. <TextBox Text="admin" Width="100">TextBox>
    9. StackPanel>
    10. <StackPanel Orientation="Horizontal">
    11. <Label Content="=电话">Label>
    12. <TextBox Text="2233">TextBox>
    13. StackPanel>
    14. StackPanel>
    15. TabItem>
    16. <TabItem Header="角色信息">
    17. <Grid Background="AliceBlue">
    18. <Grid.ColumnDefinitions>
    19. <ColumnDefinition Width="29*"/>
    20. <ColumnDefinition Width="61*"/>
    21. <ColumnDefinition Width="302*"/>
    22. Grid.ColumnDefinitions>
    23. Grid>
    24. TabItem>
    25. <TabItem Header="权限设置">
    26. <Grid Background="AliceBlue"/>
    27. TabItem>
    28. TabControl>
    29. <Button Name="bt1" Content="Button" HorizontalAlignment="Left" Margin="652,203,0,0" VerticalAlignment="Top" Click="bt1_Click"/>
    30. Grid>
    1. private void bt1_Click(object sender, RoutedEventArgs e)
    2. {
    3. //tabCl.SelectedItem=tabCl.Items[1]; // 切换选项卡
    4. if(tabCl.SelectedIndex -1)
    5. {
    6. tabCl.SelectedIndex += 1;
    7. }
    8. else
    9. {
    10. tabCl.SelectedIndex = 0;
    11. }
    12. }

    21、Frame框架

    Frame  TabControl支持导航 ,可以将一个页面导航到另一个页面,添加Page(WPF)可以实现。

    System.Windows.Navigation.NavigationWindow和 System.Windows.Controls.Frame.

    TabItem  ContentControl  直接在内部添加元素,布局成一个页面,直接将一个页面内嵌到TabItem。

    Winform TabControl   TabPage  将一个Form内嵌到TabPage。

    TabItem中不可内嵌一个Window。

    WPF中,Window为根,,内容不能是一个Window。

    Page 页是封装一页的内容

    属性

    NavigationUIVisibility   是否显示导航栏  :  

    Source是要显示的Page路径,要导航到的新内容。

    NavigationUIVisibility  是否显示导航栏:automatic   hidden  visible。

    1. <Grid>
    2. <Frame Name="fm1" Content="Frame" HorizontalAlignment="Left" Height="257" Margin="100,49,0,0"
    3. VerticalAlignment="Top" Width="562">Frame>
    4. <TabControl Name="tabCl" HorizontalAlignment="Left" Height="244" Margin="141,90,0,0" VerticalAlignment="Top" Width="398"
    5. TabStripPlacement="Top">
    6. <TabItem Header="用户信息" IsSelected="True">
    7. <Frame Source="16_1PageRolePage.xaml" NavigationUIVisibility="Visible">Frame>
    8. TabItem>
    9. <TabItem Header="角色信息" IsSelected="True">
    10. <Frame Source="16_1PageRolePage.xaml" NavigationUIVisibility="Visible">Frame>
    11. TabItem>
    12. <TabItem Header="权限设置">
    13. <Grid Background="AliceBlue"/>
    14. TabItem>
    15. TabControl>
    16. Grid>

    代码:

    1. private void Window_Loaded(object sender, RoutedEventArgs e)
    2. {
    3. // 1、直接在xaml代码中设置Source
    4. // 2、frame.Source= new Uri("", UriKind.Relative);
    5. // fm1.Source = new Uri("16_1PageRolePage.xaml",UriKind.Relative); // 相对路径
    6. //3 、先实例化Page对象
    7. _16_1PageRolePage pageRoleInfo= new _16_1PageRolePage();
    8. fm1.Navigate(pageRoleInfo);
    9. }

    22、ListView列表视图

    条目控件:数据

    ListBox  ComboBox   TabControl  ItemsControl  条目控件。

    Winform  ListView   5View

    WPF  :  ListView:用于显示数据项的列表(DataGrid)

    组织数据的结构和样式----显示数据。

    View  :GridView:ListView控件  以列 形式显示数据项 的  ”视图模式“。

           GridView属性:  Columns   ColumnHeaderTemplate  AllosColumnReorder(true)。

           列:GridViewColumn: 显示数据的列。

          属性:Herder  列标题  width  宽度    HeaderTemplate: 显示列标题内容的模板。

          CellTemplate:显示列单元格的内容的模板。

          DisplayMemberBinding    要绑定的项的   。

    将数据显示到ListView   -- 数据绑定(ItemsSource  后台代码指定   Xaml代码中设置。

    定义GridView  列集合

    UserInfos   显示到ListView  。

    上面有复选框

    1. <Grid>
    2. <ListView HorizontalAlignment="Left" Height="239" VerticalAlignment="Top" Width="564">
    3. <ListView.View>
    4. <GridView>
    5. <GridViewColumn>
    6. <GridViewColumn.Header>
    7. <CheckBox Name="ckAll" Content="全选">CheckBox>
    8. GridViewColumn.Header>
    9. <GridViewColumn.CellTemplate>
    10. <DataTemplate>
    11. <CheckBox Name="chk" Tag=" {Binding UserId" IsChecked="{Binding ElementName=chkAll,Path=IsChecked,Mode=OneWay}">CheckBox>
    12. DataTemplate>
    13. GridViewColumn.CellTemplate>
    14. GridViewColumn>
    15. <GridViewColumn Header="编号" DisplayMemberBinding="{Binding UserId}" Width="50">GridViewColumn>
    16. <GridViewColumn Header="账号" Width="70">
    17. <GridViewColumn.CellTemplate>
    18. <DataTemplate>
    19. <TextBlock Text="{Binding UserName}" Foreground="YellowGreen" HorizontalAlignment="Left"
    20. TextAlignment="Center">TextBlock>
    21. DataTemplate>
    22. GridViewColumn.CellTemplate>
    23. GridViewColumn>
    24. <GridViewColumn Header="状态" DisplayMemberBinding="{Binding UserState}">
    25. GridViewColumn>
    26. <GridViewColumn Header="部门编号" DisplayMemberBinding="{Binding Depth}">GridViewColumn>
    27. <GridViewColumn Header="年龄" DisplayMemberBinding="{Binding UserAge}" Width="50">
    28. GridViewColumn>
    29. GridView>
    30. ListView.View>
    31. ListView>
    32. Grid>

    代码:

    1. private List<UserInfo> GetUserList1()
    2. {
    3. List<UserInfo> list = new List<UserInfo>();
    4. string sql = "select UserId,UserName,UserState,UserAge from UserInfos Where Depth>0"; // 数据库语句
    5. SqlDataReader dr = SqlHelper.ExecuteReader(sql,1);
    6. while(dr.Read())
    7. {
    8. UserInfo user = new UserInfo();
    9. user.UserId = (int)dr["UserId"];
    10. user.UserName = (string)dr["UserName"];
    11. user.UserState = (int)dr["UserState"];
    12. user.UserAge = (int)dr["UserAge"];
    13. user.Depth = (int)dr["Depth"];
    14. list.Add(user);
    15. }
    16. dr.Close();
    17. return list;
    18. }
    19. }
    20. public class UserInfo
    21. {
    22. public int UserId { get; set; }
    23. public string UserName { get; set; }
    24. public int UserState { get; set; }
    25. public int UserAge { get; set; }
    26. public int Depth { get; set; }
    27. }

    23、DataGrid数据网格

    数据网格控件,选择多个项目,从中选择子项,

    DataGrid:MultiSelector   Selector

         网格控件:可以自定义网格显示的数据的控件。

         自定义的网格:列的形式

         ListView:类似网格控件  GridView  GridViewColumn

    常用属性

    HeadersVisibility: Row   Column   All   行可见  列可见   全部可见

    RowHeaderTemplate   行标题模板。

    CanUserAddRows  是否添加新行

    IsReadOnly   是否可以编辑其中的值   是否只读

    VerticalScrollBarVisibility/ HorizontalScrollBarVisibility   垂直/水平滚动条的显示

    CurrentItem   当前单元格的行绑定的数据项

    CanUserDeleteRows   是否可以删除行

    RowStyle/ CellStyle   行/单元格样式

    HeadersVisibility   行和列的可见性

    AlternatingRowBackground  交替行上使用的背景画笔,white  LightBlue  white  lightblue

    GridLinesVisibility   网格线是否可见

    VerticalGridLineBrush/HorizontalGridLinesBrush  垂直/水平网格线画笔

    RowHeaderWidth  行标题宽度  ColumnHeaderHeight  列标题宽度  RowHeight 行高度

    AutoGenerateColumns  是否自动创建列

    SelectionUnit/  SelectionMode   选择单元(单元格、行或两者)单选或多选。

    DataGrid中的列:

    DataGridTextColumn:  文本显示内容,指定的数据类型为String

    DataGridCheckBoxColumn   复选框的显示内容,指定的数据类型为Boolean

    DataGridComboBoxColumn  下拉列表的形式显示内容,指定的数据类型为Enum

    DataGridHyperlinkColumn  超链接的显示内容,指定的数据类型为Uri

    DataGridTemplateColumn   模板列:自定义显示样式。

    DataGrid 数据绑定:  

    用户显示绑定ItemsSource  /  ComboBox的绑定

    用户列表数据显示到 DataGrid

    DeptId   部门名称   ,重新选择

    XAML中设置ItemsSource

    属性设置;

    XAML:

    1. <Grid>
    2. <DataGrid Name="dgList" HeadersVisibility="All" AutoGenerateColumns="False"
    3. AlternatingRowBackground="Yellow" CanUserAddRows="True" IsReadOnly="True"
    4. VerticalScrollBarVisibility="Visible" AlternationCount="2" GridLinesVisibility="Horizontal" SelectionUnit="Cell"
    5. SelectionMode="Single" RowHeaderWidth="20" ItemsSource="{Binding UserList2}">
    6. <DataGrid.RowStyle>
    7. <Style TargetType="DataGridRow">
    8. <Setter Property="Background" Value="Transparent">Setter>
    9. <Style.Triggers>
    10. <Trigger Property="ItemsControl.AlternationIndex" Value="0">
    11. <Setter Property="Background" Value="LightGray">Setter>
    12. Trigger>
    13. <Trigger Property="ItemsControl.AlternationIndex" Value="1">
    14. <Setter Property="Background" Value="LightBlue">Setter>
    15. Trigger>
    16. Style.Triggers>
    17. Style>
    18. DataGrid.RowStyle>
    19. <DataGrid.Columns>
    20. <DataGridTextColumn Header="编号" Binding="{Binding UserId}" Width="50">DataGridTextColumn>
    21. <DataGridTextColumn Header="姓名" Binding="{Binding UserName}" Width="80">
    22. <DataGridTextColumn.HeaderTemplate>
    23. <DataTemplate>
    24. <TextBlock Text="{Binding}" Foreground="Red">TextBlock>
    25. DataTemplate>
    26. DataGridTextColumn.HeaderTemplate>
    27. DataGridTextColumn>
    28. <DataGridCheckBoxColumn Header="状态" Binding="{Binding UserState}">DataGridCheckBoxColumn>
    29. <DataGridComboBoxColumn x:Name="colDepth" Header="部门" SelectedValueBinding="{Binding DepthId}" Width="100"
    30. DisplayMemberPath=" DeptName" SelectedValuePath="DepthId"
    31. ItemsSource="{Binding DeptList2,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}">
    32. <DataGridComboBoxColumn.ElementStyle>
    33. <Style TargetType="ComboBox">
    34. <Setter Property="ItemsSource" Value="{Binding DataContext.DeptList,RelativeSource={RelativeSource
    35. Mode=FindAncestor,AncestorType=Window}}">Setter>
    36. Style>
    37. DataGridComboBoxColumn.ElementStyle>
    38. DataGridComboBoxColumn>
    39. <DataGridTemplateColumn Header="年龄" Width="60">
    40. <DataGridTemplateColumn.CellTemplate>
    41. <DataTemplate>
    42. <Label Content="{Binding UserAge}" Foreground="Green" Background="LightBlue">Label>
    43. DataTemplate>
    44. DataGridTemplateColumn.CellTemplate>
    45. <DataGridTemplateColumn.CellEditingTemplate>
    46. <DataTemplate>
    47. <TextBox Text="{Binding UserName}">TextBox>
    48. DataTemplate>
    49. DataGridTemplateColumn.CellEditingTemplate>
    50. DataGridTemplateColumn>
    51. DataGrid.Columns>
    52. DataGrid>
    53. Grid>

    24、Menu

    简介:Windows菜单控件,控件可用于按层次组织与命令和事件处理程序关联的元素。

    常用属性:IsMainMenu  是否接收菜单激活通知  True  按alt  或f10激活 如果为false。

    MenuItem介绍 :Menu  控件中的可选项,, 带标题的条目控件。

    父类: HeaderedItemsControl

            CommandParameter   Icon  Header

                  InputGestureText:

    InputGestureText="Ctrl+R"   快捷键

     Click事件:   

    打开角色管理界面

    页面.show();

    Command命令

    1. <Window.Resources>
    2. <RoutedUICommand x:Key="cmdRole"/>
    3. <RoutedUICommand x:Key="cmdUser"/>
    4. Window.Resources>
    5. <Window.InputBindings>
    6. <KeyBinding Command="{StaticResource cmdRole}" Gesture="Ctrl+R">KeyBinding>
    7. Window.InputBindings>
    8. <Window.CommandBindings>
    9. <CommandBinding Command="{StaticResource cmdRole}" Executed="miRole_Click"/>
    10. <CommandBinding Command="{StaticResource cmdUser}" Executed="miUser_Click"/>
    11. Window.CommandBindings>
    12. <Grid>
    13. <Menu Height="30" VerticalAlignment="Top" IsMainMenu="False">
    14. <MenuItem Header="系统管理">
    15. <MenuItem Name="miRole" Header="角色管理" Command="{StaticResource cmdRole}"
    16. InputGestureText="Ctrl+R">
    17. <MenuItem.Icon>
    18. <Image Source="image/12window.png">Image>
    19. MenuItem.Icon>
    20. MenuItem>
    21. <MenuItem Header="用户管理" Command="{StaticResource cmdUser}">MenuItem>
    22. <MenuItem Header="菜单管理">MenuItem>
    23. <MenuItem Header="权限管理">MenuItem>
    24. <MenuItem Header="角色">MenuItem>
    25. MenuItem>
    26. <MenuItem Header="基础资料">
    27. <MenuItem Header="商品管理">
    28. <MenuItem Header="商品类别">MenuItem>
    29. <MenuItem Header="商品名称">MenuItem>
    30. MenuItem>
    31. <MenuItem Header="仓库管理">MenuItem>
    32. <MenuItem Header="单位管理">MenuItem>
    33. <MenuItem Header="入库设置">MenuItem>
    34. MenuItem>
    35. <MenuItem Header="业务管理">MenuItem>
    36. <MenuItem Header="查询中心">
    37. <MenuItem Header="查询姓名">MenuItem>
    38. <MenuItem Header="查询资料">MenuItem>
    39. <MenuItem Header="查询性别">MenuItem>
    40. <MenuItem Header="查询年龄">MenuItem>
    41. MenuItem>
    42. Menu>
    43. Grid>

    控件使用(一个

    25、动态生成菜单项

    动态生成菜单项:递归加载菜单数据、分层数据模板;

    获取菜单数据:按层次结构组织的数据列表。

    菜单模型: 编号,名称  父类单编号  快捷键

    菜单项模型:百年好  名称  快捷键    子菜单列表

    数据模板:分层数据模板   HeaderedItemsControl   Menu  TreeView

    HierarchicalDataTemplate(分层数据模板):支持HeaderedItemsCOntrol的数据绑定,就是定义分层数据的模板,一般应用在MenuItem或TreeViewItem。

    父类:DataTemplate

    属性:  ItemsSource 数据模板的绑定  ItemTemplate以指示如何显示数据层次结构中的下一个界别中的项目 ItemContainerStyle应用与每个子项的项容器  AlternationCount交替项的子项目的容器的数量。

    1. <Window.Resources>
    2. <RoutedUICommand x:Key="cmdUser">RoutedUICommand>
    3. Window.Resources>
    4. <Window.CommandBindings>
    5. <CommandBinding Command="{StaticResource cmdUser}" Executed="CommandBinding_Executed">CommandBinding>
    6. Window.CommandBindings>
    7. <Grid>
    8. <Menu HorizontalAlignment="Left" Height="30" Margin="0" VerticalAlignment="Top" BorderBrush="LightBlue"
    9. BorderThickness="1" ItemsSource="{Binding MenuList}">
    10. <Menu.ItemContainerStyle>
    11. <Style TargetType="{x:Type MenuItem}">
    12. <Setter Property="InputGestureText" Value="{Binding MKey}">Setter>
    13. <Setter Property="InputGestureText" Value="{Binding MKey1}">Setter>
    14. Style>
    15. Menu.ItemContainerStyle>
    16. <Menu.ItemTemplate>
    17. <HierarchicalDataTemplate>
    18. <TextBlock Text="{Binding MenuName}" VerticalAlignment="Center">TextBlock>
    19. HierarchicalDataTemplate>
    20. Menu.ItemTemplate>
    21. Menu>
    22. Grid>

    26、ContextMenu文本菜单

    右键出现如下:

    父类:MenuBase   MenuItem   (HeaderedItemsControl)  ItemsControl  特定于某个元素之上的功能菜单。右键菜单,上下文菜单。

    属性:HorizontalOffset   verticalOffset  右键菜单控件相对于带年纪位置的水平、垂直Label(右键菜单的目标元素)

    快捷键相应:与命令或事件处理程序关联起来。

    应用:不独立,依赖于某个元素

    1. <Grid>
    2. <Label Content="用户管理" HorizontalAlignment="Left" Margin="184,97,0,0"
    3. VerticalAlignment="Top" Height="33" Width="73" BorderBrush="Blue" BorderThickness="1">
    4. <Label.ContextMenu>
    5. <ContextMenu HorizontalOffset="10" VerticalAlignment="Top">
    6. <MenuItem Header="打开页面">MenuItem>
    7. <MenuItem Header="操作">
    8. <MenuItem Header="赋值">MenuItem>
    9. <MenuItem Header="剪切">MenuItem>
    10. MenuItem>
    11. ContextMenu>
    12. Label.ContextMenu>
    13. Label>
    14. Grid>

    27、TreeView树视图

    属性介绍:树形控件

    TreeView   父类:  ItemsControl  -- 条目控件

    MenuItem:  派生于HeaderedItemsControl

    按层次结构组织数据

    SelectedValue选择项的值

    SelectedValuePath   菜单名称  编号  (列名或属性名)

    TreeViewItem被选中触发

    1. private void tv1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    2. {
    3. var val = e.NewValue as TreeViewItem;
    4. MessageBox.Show(val.Header.ToString());
    5. }
    1. private void tv1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    2. {
    3. var val = e.NewValue as TreeViewItem;
    4. MessageBox.Show(val.Header.ToString());
    5. }
    6. private void Window_Loaded(object sender, RoutedEventArgs e)
    7. {
    8. TreeViewItem tv = new TreeViewItem();
    9. tv.Header= "进销存系统";
    10. tv1.Items.Add(tv);
    11. TreeViewItem tv2 = new TreeViewItem();
    12. tv2.Header = "用户管理";
    13. tv1.Items.Add(tv2);
    14. TreeViewItem tv3 = new TreeViewItem();
    15. tv3.Header = "角色信息";
    16. tv1.Items.Add(tv3);
    17. }

    进销存系统   系统管理   用户管理

    动态模板

    1. <Window.Resources>
    2. <RoutedUICommand x:Key="cmdUser">RoutedUICommand>
    3. Window.Resources>
    4. <Window.CommandBindings>
    5. <CommandBinding Command="{StaticResource cmdUser}" Executed="CommandBinding_Executed">CommandBinding>
    6. Window.CommandBindings>
    7. <Grid>
    8. <TreeView Name="tvList" HorizontalAlignment="Left" Height="30" Margin="0" VerticalAlignment="Top" BorderBrush="LightBlue"
    9. BorderThickness="1">
    10. <TreeView.ItemTemplate>
    11. <HierarchicalDataTemplate DataType="{x:Type model:MenuItemModel}" ItemsSource="{Binding SubItems}">
    12. <TextBlock Text="{Binding MenuName}" VerticalAlignment="Center">TextBlock>
    13. HierarchicalDataTemplate>
    14. TreeView.ItemTemplate>
    15. TreeView>
    16. Grid>

    27、ToolBar工具条

    Orientation  指示排列方向

    Band  BandIndex

    TollBarTray

    代码:

    1. <Grid>
    2. <ToolBar HorizontalAlignment="Left" Height="36" Margin="10,10,0,0" Width="695"
    3. IsOverflowOpen="True">
    4. <Button Content="新建">Button>
    5. <Separator/>
    6. <Image Source="image/12window.png" Width="20" Height="20">Image>
    7. <CheckBox Content="是否保存" IsChecked="True" Margin="10,0">CheckBox>
    8. <Separator/>
    9. <RadioButton Name="rbRed1" ToolTip="Red" Command="{StaticResource setColor}">
    10. <RadioButton.Content>
    11. <Rectangle Width="10" Height="10" Fill="Red">Rectangle>
    12. RadioButton.Content>
    13. RadioButton>
    14. <RadioButton ToolTip="Yellow" Command="{StaticResource setColor}">
    15. <RadioButton.Content>
    16. <Rectangle Width="10" Height="10" Fill="Yellow">Rectangle>
    17. RadioButton.Content>
    18. RadioButton>
    19. <Separator/>
    20. <ComboBoxItem Content="选择" VerticalAlignment="Center"
    21. PreviewMouseLeftButtonDown="ComboBoxItem_MouseLeftButtonDown">ComboBoxItem>
    22. ToolBar>
    23. <Label Name="lb1" Content="我是测试文本" Margin="103,78,0,0" VerticalAlignment="Top">Label>
    24. Grid>

    IsOverFlowOpen

    如果溢出区可见,则为 true;否则为 false

    ToolBarTray:  

    1. <Window.Resources>
    2. <RoutedUICommand x:Key="setColor">RoutedUICommand>
    3. Window.Resources>
    4. <Window.CommandBindings>
    5. <CommandBinding Command="{StaticResource setColor}" Executed="setColor_Executed">CommandBinding>
    6. Window.CommandBindings>
    7. <Grid>
    8. <Grid.ColumnDefinitions>
    9. <ColumnDefinition Width="0*"/>
    10. <ColumnDefinition Width="0*"/>
    11. <ColumnDefinition/>
    12. Grid.ColumnDefinitions>
    13. <ToolBarTray Orientation="Horizontal" Grid.ColumnSpan="3">
    14. <ToolBar HorizontalAlignment="Left" Height="36" Margin="10,10,0,0" Width="695"
    15. IsOverflowOpen="True" Band="0" BandIndex="0">
    16. <Button Content="新建">Button>
    17. <Separator/>
    18. <Image Source="image/12window.png" Width="20" Height="20">Image>
    19. <CheckBox Content="是否保存" IsChecked="True" Margin="10,0">CheckBox>
    20. <Separator/>
    21. <RadioButton Name="rbRed1" ToolTip="Red" Command="{StaticResource setColor}">
    22. <RadioButton.Content>
    23. <Rectangle Width="10" Height="10" Fill="Red">Rectangle>
    24. RadioButton.Content>
    25. RadioButton>
    26. <RadioButton ToolTip="Yellow" Command="{StaticResource setColor}">
    27. <RadioButton.Content>
    28. <Rectangle Width="10" Height="10" Fill="Yellow">Rectangle>
    29. RadioButton.Content>
    30. RadioButton>
    31. <Separator/>
    32. <ComboBoxItem Content="选择" VerticalAlignment="Center"
    33. PreviewMouseLeftButtonDown="ComboBoxItem_MouseLeftButtonDown">ComboBoxItem>
    34. ToolBar>
    35. <ToolBar HorizontalAlignment="Left" Height="36" VerticalAlignment="Top"
    36. IsOverflowOpen="True" Band="0" BandIndex="1">
    37. <Button Content="复制">Button>
    38. <Button Content="剪切">Button>
    39. ToolBar>
    40. ToolBarTray>
    41. Grid>

    29、statusBar状态栏

    StatusBar:  应用程序窗体中的水平栏中显示项和信息的kongj (状态栏)。

    父类:ItemsControl。

    项:StatusBarItem   StatusBar中的项。

    进度过程:

    简单的状态栏:登录者  当前时间   版权信息   进度。

    1. <Grid>
    2. <StatusBar HorizontalAlignment="Left" VerticalAlignment="Stretch" Height="30">
    3. <StatusBarItem Content="登陆者">StatusBarItem>
    4. <StatusBarItem>
    5. <StackPanel Orientation="Horizontal">
    6. <Label Content="当前时间">Label>
    7. <TextBlock Text="2020-02-01">TextBlock>
    8. StackPanel>
    9. StatusBarItem>
    10. <StatusBarItem>
    11. <StackPanel Orientation="Horizontal">
    12. <Label Content="加载进度">Label>
    13. <ProgressBar Name="pbar" Value="0" Width="100" Height="25">
    14. <ProgressBar.Triggers>
    15. <EventTrigger RoutedEvent="ProgressBar.Loaded">
    16. <BeginStoryboard>
    17. <Storyboard>
    18. <DoubleAnimation From="0" To="{Binding ElementName=pbar,Path=Maximum}" Storyboard.TargetName="pbar"
    19. Storyboard.TargetProperty="Value"
    20. Duration="0:0:5">DoubleAnimation>
    21. Storyboard>
    22. BeginStoryboard>
    23. EventTrigger>
    24. ProgressBar.Triggers>
    25. ProgressBar>
    26. StackPanel>
    27. StatusBarItem>
    28. StatusBar>
    29. Grid>

    29、MediaElement媒体元素

    网易云音乐播放器

    链接:  WPF 媒体播放器(MediaElement)实例,实现进度和音量控制 - 天马3798 - 博客园 (cnblogs.com)

    WPF 媒体播放器(MediaElement)实例,实现进度和音量控制 - 天马3798 - 博客园 (cnblogs.com)

    属性

    LoadedBehavior 加载行为 (Manual 手动控制 Play Close(关闭并释放) Pause Stop关闭但不释放)

    Position 通过媒体的播放时间获取或设置进度的当前位置。

    CanPause(get) IsBuffering 是否缓冲媒体 HasAudio/HasVideo 是否有音频/视频

    SpeedRatio 媒体的速率 UnloadedBehavior 卸载行为

    Clock 与相关联的时钟 Balance 扬声器的音量比 Volume 媒体的音量

    StretchDirection 拉伸值,该值指定该元素的方向 Source 媒体源 IsMuted 是否已静音

    WPF加绝对路径,否则无法播放

    1. <Window x:Class="WpfAppTest.MediaElementWindow"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    6. xmlns:local="clr-namespace:WpfAppTest"
    7. mc:Ignorable="d"
    8. Title="MediaElementWindow" Height="450" Width="800">
    9. <Grid>
    10. <Border BorderThickness="2" BorderBrush="YellowGreen" HorizontalAlignment="Left" Height="275" Margin="43,26,0,0" VerticalAlignment="Top" Width="583">
    11. <MediaElement Source="绝对路径/medias/tongyao1.mp4" IsMuted="False" Volume="0.3" SpeedRatio="1" UnloadedBehavior="Stop" Balance="-0.6" StretchDirection="Both" Stretch="Fill" />
    12. Border>
    13. Grid>
    14. Window>
    1. <Grid>
    2. <MediaElement x:Name="mediaElement" Source="play123.mp4" LoadedBehavior="Manual" Width="400" Height="225"
    3. MediaOpened="mediaElement_MediaOpened" MediaFailed="mediaElement_MediaFailed"/>
    4. <Button Content="Play" HorizontalAlignment="Left" Margin="444,12,0,0" VerticalAlignment="Top" Width="75"
    5. Click="Button_Click" />
    6. Grid>

    代码:

    1. private void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
    2. {
    3. mediaElement.Source = new Uri("E:\\SoftStudy\\C#\\C#\\基础\\01WPF基础\\02控件_1\\image\\play123.mp4", UriKind.Relative);
    4. mediaElement.Play();
    5. }
    6. private void mediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
    7. {
    8. MessageBox.Show("Media failed to load: " + e.ErrorException.Message);
    9. }
    10. private void Button_Click(object sender, RoutedEventArgs e)
    11. {
    12. //if (mediaElement.SetCurrentValue == MediaState.Paused || mediaElement.CurrentState == MediaState.Stopped)
    13. //{
    14. // mediaElement.Play();
    15. //}
    16. //else
    17. //{
    18. // mediaElement.Pause();
    19. //}
    20. mediaElement.Source = new Uri("E:\\SoftStudy\\C#\\C#\\基础\\01WPF基础\\02控件_1\\image\\play123.mp4", UriKind.Absolute);
    21. mediaElement.Play();
    22. }

    播放器案例

    记载时,创建一个计时器,播放位置调整、时间文本更新

    打开:  选择播放数据源,加载完毕,自动播放。

    播放或暂停-

    停止:回到原来位置,停止播放。

    快进:前进10s   后退:10s

    OpenFileDialog ofd = new OpenFileDialog();

    打开文件对话框,

    参考:2021-08-14 WPF控件专题 MediaElement 控件详解_qq61972345e36b7的技术博客_51CTO博客

    控件案例   别忘记Loaded

    1. <Window x:Class="WpfAppTest.MediaElementWindow2"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    6. xmlns:local="clr-namespace:WpfAppTest"
    7. mc:Ignorable="d"
    8. Title="MediaElementWindow2" Height="450" Width="800" Loaded="Window_Loaded">
    9. <Window.Resources>
    10. <Style x:Key="btnStyle" TargetType="Button">
    11. <Setter Property="Background">
    12. <Setter.Value>
    13. <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
    14. <GradientStop Offset="0" Color="White"/>
    15. <GradientStop Offset="0.444" Color="#FF53897A"/>
    16. LinearGradientBrush>
    17. Setter.Value>
    18. Setter>
    19. <Setter Property="FontStyle" Value="Oblique"/>
    20. <Setter Property="Margin" Value="5"/>
    21. <Setter Property="Width" Value="60"/>
    22. <Setter Property="Foreground" Value="Gold"/>
    23. <Style.Triggers>
    24. <Trigger Property="Button.IsMouseOver" Value="True">
    25. <Setter Property="Foreground" Value="Black"/>
    26. Trigger>
    27. Style.Triggers>
    28. Style>
    29. Window.Resources>
    30. <Grid>
    31. <StackPanel>
    32. <Border Background="Black" BorderThickness="3" HorizontalAlignment="Center" Height="300" VerticalAlignment="Top" Width="500">
    33. <Border.Effect>
    34. <DropShadowEffect Color="#FFE4CC8D"/>
    35. Border.Effect>
    36. <Border.BorderBrush>
    37. <LinearGradientBrush StartPoint="1,0" EndPoint="1,1">
    38. <GradientStop Offset="0" Color="White"/>
    39. <GradientStop Offset="0.5" Color="Gold"/>
    40. LinearGradientBrush>
    41. Border.BorderBrush>
    42. <MediaElement Name="me" LoadedBehavior="Manual" SpeedRatio="1" Stretch="Fill" UnloadedBehavior="Stop" ScrubbingEnabled="True" Volume="{Binding ElementName=volumeSlider,Path=Value}" Balance="0.6" MouseLeftButtonDown="Me_MouseLeftButtonDown" MediaOpened="Me_MediaOpened" MediaEnded="Me_MediaEnded" />
    43. Border>
    44. <StackPanel Margin="0,10,0,0" Orientation="Horizontal" HorizontalAlignment="Center">
    45. <TextBlock Text="播放进度" Foreground="Gold" Margin="5"/>
    46. <Slider x:Name="posSlider" Minimum="0" Width="190" Value="{Binding ElementName=me,Path=Position}" IsMoveToPointEnabled="True" PreviewMouseLeftButtonUp="PosSlider_PreviewMouseLeftButtonUp" />
    47. <TextBlock Text="音量" Foreground="Gold" Margin="20,0,0,0"/>
    48. <Slider x:Name="volumeSlider" Margin="10,0" Minimum="0" Maximum="1" Value="0.5" Width="167" />
    49. StackPanel>
    50. <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,10">
    51. <Button x:Name="openBtn" Content="打开" Style="{StaticResource btnStyle}" Click="OpenBtn_Click"
    52. />
    53. <Button x:Name="playBtn" Content="播放" Style="{StaticResource btnStyle}" Click="PlayBtn_Click"
    54. />
    55. <Button x:Name="stopBtn" Content="停止" Style="{StaticResource btnStyle}" Click="StopBtn_Click"
    56. />
    57. <Button x:Name="backBtn" Content="快退" Style="{StaticResource btnStyle}" Click="BackBtn_Click"
    58. />
    59. <Button x:Name="forwardBtn" Content="快进" Style="{StaticResource btnStyle}" Click="ForwardBtn_Click"
    60. />
    61. <Label Name="lblTime" Width="100" Height="30" Content="00:04">Label>
    62. StackPanel>
    63. StackPanel>
    64. Grid>
    65. Window>

    主程序代码

    1. System.Timers.Timer timer = null;
    2. private void Window_Loaded(object sender, RoutedEventArgs e)
    3. {
    4. timer = new System.Timers.Timer();
    5. timer.Interval = 1000;
    6. timer.Elapsed += Timer_Elapsed;
    7. }
    8. private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    9. {
    10. //子线程执行
    11. this.Dispatcher.Invoke(new Action(() =>
    12. {
    13. //主线程
    14. posSlider.Value = me.Position.TotalSeconds;
    15. SetTime();
    16. }
    17. ));
    18. }
    19. ///
    20. /// 设置时间文本框的值
    21. ///
    22. private void SetTime()
    23. {
    24. lblTime.Content = string.Format("{0:00}:{1:00}:{2:00}", me.Position.Hours, me.Position.Minutes, me.Position.Seconds);
    25. }
    26. //选择播放文件
    27. private void OpenBtn_Click(object sender, RoutedEventArgs e)
    28. {
    29. OpenFileDialog ofd = new OpenFileDialog();
    30. ofd.Filter = @"视频文件(*.avi格式)|*.avi|视频文件(*.wav格式)|*.wav|视频文件(*.wmv格式)|*.wmv|视频文件(*.mp4格式)|*.mp4|All Files|*.*";
    31. if (ofd.ShowDialog() == false)
    32. {
    33. return;
    34. }
    35. string filePath = "";
    36. filePath = ofd.FileName;
    37. if (filePath == "")
    38. return;
    39. //设置媒体源
    40. me.Source = new Uri(filePath, UriKind.Absolute);
    41. playBtn.IsEnabled = true;
    42. me.Play();
    43. timer.Start();
    44. playBtn.Content = "暂停";
    45. }
    46. //播放或暂停
    47. private void PlayBtn_Click(object sender, RoutedEventArgs e)
    48. {
    49. SetPlayer(true);
    50. PlayPause();
    51. }
    52. ///
    53. /// 播放或暂停
    54. ///
    55. private void PlayPause()
    56. {
    57. if (playBtn.Content.ToString() == "播放")
    58. {
    59. me.Play();
    60. timer.Start();
    61. playBtn.Content = "暂停";
    62. me.ToolTip = "单击暂停";
    63. }
    64. else
    65. {
    66. me.Pause();
    67. timer.Stop();
    68. playBtn.Content = "播放";
    69. me.ToolTip = "单击播放";
    70. SetTime();
    71. }
    72. }
    73. ///
    74. /// 设置操作按钮的可用状态
    75. ///
    76. ///
    77. private void SetPlayer(bool bl)
    78. {
    79. stopBtn.IsEnabled = bl;
    80. playBtn.IsEnabled = bl;
    81. backBtn.IsEnabled = bl;
    82. forwardBtn.IsEnabled = bl;
    83. }
    84. ///
    85. /// 停止
    86. ///
    87. ///
    88. ///
    89. private void StopBtn_Click(object sender, RoutedEventArgs e)
    90. {
    91. me.Stop();
    92. posSlider.Value = 0;
    93. lblTime.Content = "0:0:0";
    94. playBtn.Content = "播放";
    95. timer.Stop();
    96. }
    97. ///
    98. /// 快进 当前播放位置前进10s
    99. ///
    100. ///
    101. ///
    102. private void ForwardBtn_Click(object sender, RoutedEventArgs e)
    103. {
    104. me.Pause();
    105. timer.Stop();
    106. me.Position = me.Position + TimeSpan.FromSeconds(10);
    107. SetTime();
    108. me.Play();
    109. timer.Start();
    110. }
    111. ///
    112. /// 快退
    113. ///
    114. ///
    115. ///
    116. private void BackBtn_Click(object sender, RoutedEventArgs e)
    117. {
    118. me.Pause();
    119. timer.Stop();
    120. me.Position = me.Position - TimeSpan.FromSeconds(10);
    121. SetTime();
    122. me.Play();
    123. timer.Start();
    124. }
    125. private void Me_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    126. {
    127. PlayPause();
    128. }
    129. ///
    130. /// 媒体加载完毕后
    131. ///
    132. ///
    133. ///
    134. private void Me_MediaOpened(object sender, RoutedEventArgs e)
    135. {
    136. posSlider.Maximum = me.NaturalDuration.TimeSpan.TotalSeconds;
    137. lblTime.Content = "0:0:0";
    138. SetPlayer(true);
    139. }
    140. ///
    141. ///拖动播放进度
    142. ///
    143. ///
    144. ///
    145. private void PosSlider_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    146. {
    147. me.Pause();
    148. timer.Stop();
    149. int val = (int)posSlider.Value;
    150. me.Position = new TimeSpan(0, 0, 0, val);
    151. SetTime();
    152. me.Play();
    153. timer.Start();
    154. }
    155. private void Me_MediaEnded(object sender, RoutedEventArgs e)
    156. {
    157. MessageBox.Show("播放结束");
    158. timer.Stop();
    159. }

    30、RichTextBox超文本

    Document 获取或设置RichTextBox的System.Window.Documents.FlowDocument  

    属性:

    FlowDocument:

        inline   Run   Hyperlink   

    block   paragraph    section    blockuicontainer

    FlowDocument:

    Block  Paragraph   Run   Section    Hyperlink   InlineUIContainer   BlockUIContainer

    1. <Grid>
    2. <RichTextBox Name="rtbContent" HorizontalAlignment="Left" Height="229" Margin="70,70,0,0"
    3. VerticalAlignment="Top" Width="400" IsDocumentEnabled="True">
    4. <FlowDocument>
    5. <Paragraph TextIndent="24">
    6. <Run Text="RichTextBox">Run>
    7. Paragraph>
    8. <Paragraph>
    9. <Run Text="RichTextBox">Run>
    10. <Hyperlink Click="Hyperlink_Click">百度一下Hyperlink>
    11. Paragraph>
    12. <Paragraph>
    13. <Run Text="另一个文本">Run>
    14. Paragraph>
    15. <Section>Section>
    16. FlowDocument>
    17. RichTextBox>
    18. <Button Content="获取内容" Margin="547,88,188,323" Height="30"/>
    19. Grid>

    代码:

    1. private void Hyperlink_Click(object sender, RoutedEventArgs e)
    2. {
    3. Process proc=new Process();
    4. proc.StartInfo.FileName = "http://www.baidu.com";
    5. proc.Start();
    6. }
    7. private void GetText_Click(object sender, RoutedEventArgs e)
    8. {
    9. TextRange range = new TextRange(rtbContent.Document.ContentStart,rtbContent.Document.ContentEnd);
    10. string contentText = range.Text; // 纯文本内容
    11. MessageBox.Show(contentText);
    12. }

  • 相关阅读:
    探索数字安全的卓越之选 - Digicert证书
    SpringBoot中对Spring AOP的实现
    Google Hacking搜索
    Python数据库编程全指南SQLite和MySQL实践
    我看见了黑洞
    [qiankun]微前端实现方案
    356页14万字高端商业办公综合楼弱电智能化系统2022版
    java简单实现AIDL进程通信
    MyBatis框架简介
    Unittest-生成HTML测试报告
  • 原文地址:https://blog.csdn.net/qq_45085522/article/details/138258138