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里边创建函数
private void Window_Loaded(object sender, RoutedEventArgs e)
{
RadioButton rbtn =new RadioButton();
rbtn.Content = "主任";
rbtn.GroupName = "role";
grid.Children.Add(rbtn);
rbtn.IsChecked = false;
rbtn.HorizontalAlignment = HorizontalAlignment.Left;
rbtn.VerticalAlignment = VerticalAlignment.Top;
rbtn.Margin = new Thickness(500, 237, 0, 0);
//this.grid.Children.Add(rbtn);
}
Closing:
MoseDoubleClick:
MouseLeftButtonDown:
MouseLeftButtonUp:
MouseLeftButtonUp:
MouseRightButtonDown:
<Window x:Class="_01WPF基础.MainWindow"
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:_01WPF基础"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" WindowStartupLocation="CenterScreen" WindowState="Normal" Topmost="True"
Icon="image/12window.png" Loaded="Window_Loaded">
上述为Window的属性
3.2、标签文本框内容控件
Label 文本标签 contextControl
TextBox 特殊内容
PasswordBox
WPF允许空间没名称,但是引用时候需要命名
<Window x:Class="_01WPF基础.MainWindow"
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:_01WPF基础"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" WindowStartupLocation="CenterScreen" WindowState="Normal" Topmost="True"
Icon="image/12window.png" Loaded="Window_Loaded">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel Grid.ColumnSpan="2" Margin="0,10,533,-10">
<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"
Foreground="{Binding ValueColor}"/>
<Label x:Name="用户名" Content="登录" HorizontalAlignment="Left" Margin="20,80,0,0" Width="46" RenderTransformOrigin="0.476,-0.105" />
<Button Content="Button" HorizontalAlignment="Left" Margin="22,80,0,0" Command="{Binding ValueCommand}"
CommandParameter="123" RenderTransformOrigin="0.197,0.579"/>
<Button HorizontalAlignment="Left" Margin="22,42,0,0" VerticalAlignment="Top" Command="{Binding ValueCommand}"
CommandParameter="123" RenderTransformOrigin="0.197,0.579">
Buttonr1
<!--content也可以放在这里-->
</Button>
</StackPanel>
<!--<ListBox></ListBox>-->
<!--<ListView></ListView>
<DataGrid></DataGrid>-->
<ItemsControl Grid.Column="1" ItemsSource="{Binding ValueList}" Background="LightGray" HorizontalAlignment="Right" Width="400">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Value}"></TextBlock>
<TextBlock Text="{Binding Name}"></TextBlock>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
1、Button按钮
Button的属性
BorderBrush: 背景颜色 ,例如:BorderBrush="Red"
BorderThickness: 背景厚度 ,例如 BorderThickness=“1”
Foreground: 字体颜色
HorizontalAlignment: 水平对齐
fontStretch:字体拉伸
Button.BackGround:背景色或者图片
Foreground: 前景色, 文本字体,大小
IsDefault="true":敲击Enter触发
IsCancel="true": 敲击Enter触发
按钮背景图片:
<Button HorizontalAlignment="Left" Margin="22,42,0,0" VerticalAlignment="Top" Command="{Binding ValueCommand}"
CommandParameter="123" RenderTransformOrigin="0.197,0.579">
<Button.Background>
<ImageBrush ImageSource="image/12window.png"></ImageBrush>
</Button.Background>
<!--content也可以放在这里-->
</Button>
2、MessageBox
消息框
按钮事件显示框
3、RadioButton
GroupBox:互斥
属性:
GroupName="role" 组名命名相同则互斥,设置一个组名不同组名,它们不具备互斥的关系。
点击RadioButton触发Checked事件则传入的是一个对象Object这个是传入的控件本身:
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
MessageBox.Show((sender as RadioButton).Content.ToString());
}
<Grid>
<Button Name="btnLogin" Content="登录" HorizontalAlignment="Left" Margin="179,276,0,129" Width="60" Height="30">
<Button.Background>
<ImageBrush ImageSource="image/12window.png"></ImageBrush>
</Button.Background>
</Button>
<TextBox Name="txtUName" HorizontalAlignment="Left" Margin="209,166,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<Label Content="账户" HorizontalAlignment="Left" Margin="144,166,0,0" VerticalAlignment="Top"/>
<Label Content="密码" HorizontalAlignment="Left" Margin="147,0,0,0" VerticalAlignment="Center"/>
<Button Name="BtnCancel" Content="取消" HorizontalAlignment="Left" Margin="288,276,0,0" VerticalAlignment="Top" Click="BtnCancel_Click" Width="60" Height="30"/>
<PasswordBox Name="txtUPwd" HorizontalAlignment="Left" Margin="211,205,0,0" Password="123456" PasswordChar="*" VerticalAlignment="Top" Width="120"/>
<RadioButton Content="管理员" HorizontalAlignment="Left" GroupName="role" Margin="147,242,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked"/>
<RadioButton Content="教师" HorizontalAlignment="Left" GroupName="role" Margin="288,242,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked"/>
<RadioButton Content="学生" HorizontalAlignment="Left" GroupName="role" Margin="408,237,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked"/>
</Grid>
4、CheckBox复选框
复选框:允许选择多个
常用属性: Content Name IsChecked(True,False,Null) IsThreeState="True"
事件:常见的事件有Checked Click UnChecked
XAML文件程序:
<CheckBox Name="chkSport" Content="体育" IsChecked="False" HorizontalAlignment="Left" Margin="460,256,0,0" VerticalAlignment="Top" IsThreeState="True"/>
<CheckBox Content="唱歌" IsChecked="False" HorizontalAlignment="Left" Margin="500,256,0,0" VerticalAlignment="Top" IsThreeState="True"/>
<CheckBox Content="跳舞" IsChecked="False" HorizontalAlignment="Left" Margin="559,256,0,0" VerticalAlignment="Top" IsThreeState="True"/>
<Button Content="获取" HorizontalAlignment="Left" Margin="504,325,0,0" VerticalAlignment="Top" Click="Button_Click"/>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void BtnCancel_Click(object sender, RoutedEventArgs e)
{
}
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
MessageBox.Show((sender as RadioButton).Content.ToString());
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
RadioButton rbtn =new RadioButton();
rbtn.Content = "主任";
rbtn.GroupName = "role";
grid.Children.Add(rbtn);
rbtn.IsChecked = false;
rbtn.HorizontalAlignment = HorizontalAlignment.Left;
rbtn.VerticalAlignment = VerticalAlignment.Top;
rbtn.Margin = new Thickness(500, 237, 0, 0);
//this.grid.Children.Add(rbtn);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// using System.Windows.Controls; 这个命名控件允许 <Grid></Grid>里的控件可以直接被索引,例如chkSport控件:CheckBox
// MessageBox.Show(chkSport.IsChecked.ToString());
// 获取窗口中所有勾选的CheckedBox的Content
//string strContents = "";
//foreach (UIElement ele in grid.Children)
//{
// CheckBox chb = ele as CheckBox;
// if (chb is CheckBox)
// {
// if (chb.IsChecked == true)
// {
// if (strContents != "")
// strContents += ",";
// strContents += chb.Content.ToString();
// }
// }
//}
//MessageBox.Show(strContents);
// 代码动态不回CheckBox
string[] names = { "体育", "唱歌", "跳舞" };
for (int i = 0; i < names.Length; i++)
{
CheckBox chk = new CheckBox();
chk.Content = names[i];
chk.HorizontalAlignment = HorizontalAlignment.Left;
chk.VerticalAlignment = VerticalAlignment.Top;
chk.Margin = new Thickness(40 + i * 80, 60, 0, 0);
grid.Children.Add(chk);
}
}
}
5、Image 图像控件
属性:
四种拉伸模式:
Stretch属性
四种拉伸模式:
None=0,保持内容原始大小。
Fill=1:调整内容大小以填充目标尺寸,不保留纵横比。
Uniform=2:在保留内容原有纵横比的同时调整内容的大小,以适合目标尺寸,纵横比不够的空白。
UniformToFill=3,在保留内容原有纵横比的同时调整内容的大小,以适合目标尺寸,如果目标的纵横比不同于源矩形的纵横比,则会对源内容进行裁剪以适合目标尺寸。
StretchDirection
UpOnly =0,内容仅在小于父级时扩展。如果内容较大,则不执行缩放。
DownOnly=1,内容仅在大于父级时缩放,如果内容较小,则不会执行任何扩展。
Both=2,内容将根据System.Window.Media.stretch模式进行拉伸以适应父级。
查看文件路径
6、Border边界
围绕其他控件周围 或者设置背景色,
为<Grid></Grid>设置边框
属性:下面三个属性分别为边框颜色,粗细,圆角大小
BorderBrush="Black" BorderThickness="1" CornerRadius="5"
Padding=”5“内部元素与边框的边距
<Grid>
<Border BorderBrush="Black" BorderThickness="1" CornerRadius="5" HorizontalAlignment="Left" Margin="276,129,0,0" Background="Yellow"
Padding="5" Width="100" Height="30" VerticalAlignment="Top">
<Label Content="用户名" HorizontalContentAlignment="Center"></Label>
</Border>
</Grid>
应用与布局面板一起使用,作为任意控制的边框显示,不是布局面板
只能有一个子元素
多个子元素时可以结合布局面板使用
事件:
7、下拉框ComboBox
下拉框属于条目控件(ItemsControl) 下拉框绑定,,可以通过Binding方式绑定
第一种绑定方式:
<ComboBox Name="cboClassed" HorizontalAlignment="Left" Margin="136,202,0,0" VerticalAlignment="Top"
Width="190" Height="41" IsDropDownOpen="False" Grid.ColumnSpan="2">
<ComboBoxItem Content="请选择"></ComboBoxItem>
<ComboBoxItem Content="英语版"></ComboBoxItem>
<ComboBoxItem Content="数学班"></ComboBoxItem>
<ComboBoxItem Content="软件版"></ComboBoxItem>
<ComboBoxItem Content="数据班"></ComboBoxItem>
</ComboBox>
第二种:
IsDropDownOpen="True" 下拉框在程序运行时是打开的
<ComboBox HorizontalAlignment="Left" Margin="136,231,0,0" VerticalAlignment="Top"
Width="190" Height="41" IsDropDownOpen="True">
<ComboBoxItem Content="请选择"></ComboBoxItem>
<ComboBoxItem Content="英语版"></ComboBoxItem>
<ComboBoxItem Content="数学班"></ComboBoxItem>
<ComboBoxItem Content="软件版"></ComboBoxItem>
<ComboBoxItem Content="数据班"></ComboBoxItem>
</ComboBox>
代码实现:数据库连接,,想自由Add和RemoveAt方式绑定,不要绑定数据源如下:
public _04ComboboxWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// 获取数据源
List<string> list = new List<string>(); // 连接数据库的内容
cboClasses.SelectedValuePath = "ClassId"; // 项的值对应的属性名
cboClasses.DisplayMemberPath = "ClassName"; // 项的显示文本对应的属性名
// 另一种方式,通过对list操作进行下拉框的添加和删除
//cboClasses.DataContext = list;
//cboClasses.ItemsSource = null;
//list.Add(new ClassInfo){
// CalssId = 4;
// ClassName = "音乐课";
//}
//cboClasses.ItemsSource = list;
//cboClasses.ItemsSource = list; // 指定资源
}
private void Button_Click(object sender, RoutedEventArgs e)
{
cboClassed.Items.RemoveAt(1);
}
}
指定数据源不能这样操作.3不能使用 Items.RemoveAt() 函数
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// 获取数据源
List<string> list = new List<string>(); // 连接数据库的内容
cboClasses.SelectedValuePath = "ClassId"; // 项的值对应的属性名
cboClasses.DisplayMemberPath = "ClassName"; // 项的显示文本对应的属性名
cboClasses.ItemsSource = list; // 指定资源
}
// 指定数据源不能这样操作
private void Button_Click(object sender, RoutedEventArgs e)
{
cboClasses.Items.RemoveAt(1);
}
如果想实现,则先对数据源操作再赋值
第三种绑定:
主窗口程序: DataContext 数据上下文或者数据资源
// 获取数据源
List<string> list = new List<string>(); // 连接数据库的内容
cboClasses.SelectedValuePath = "ClassId"; // 项的值对应的属性名
cboClasses.DisplayMemberPath = "ClassName"; // 项的显示文本对应的属性名
// 另一种方式,通过对list操作进行下拉框的添加和删除
cboClasses.DataContext = list;
XAML:程序,ItemsSource需要绑定
<ComboBox Name="cboClasses" HorizontalAlignment="Left" Margin="174,309,0,0" VerticalAlignment="Top" Width="120" Grid.ColumnSpan="2"
ItemsSource="{Binding }">
</ComboBox>
或者:
事件: SelectionChanged 选择改变触发
<ComboBox Name="cboClassed" HorizontalAlignment="Left" Margin="136,202,0,0" VerticalAlignment="Top"
Width="190" Height="41" IsDropDownOpen="False" Grid.ColumnSpan="2" SelectionChanged="cboClassed_SelectionChanged">
<ComboBoxItem Content="请选择"></ComboBoxItem>
<ComboBoxItem Content="英语版"></ComboBoxItem>
<ComboBoxItem Content="数学班"></ComboBoxItem>
<ComboBoxItem Content="软件版"></ComboBoxItem>
<ComboBoxItem Content="数据班"></ComboBoxItem>
</ComboBox>
代码:
private void cboClassed_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// MessageBox.Show((cboClassed.SelectedItem as ClassInfo).ClassName);
MessageBox.Show(cboClassed.SelectedItem.ToString());
}
SelectionModel : 选择模式,,选择多项还是单项。
Selection是名词还是selected这个,,一个是名词一个是被选择
8、ListBox 列表框
属性:IsDropDownOpen 启动后是否打开,下拉
包含可选择的列表:: 属于条目控件 ItemsControl
绑定方式:
绑定方式和ComboBox类似,一样,可以添加任意数据类型的值作为项
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ltbox.ItemsSource=new List<ListBoxItem>();
ltbox.SelectedValuePath = "1";
ltbox.DisplayMemberPath= "音乐";
}
<Grid>
<ListBox Name="ltbox" HorizontalAlignment="Left" Margin=" 120,120,0,0" VerticalAlignment="Top" Width="160" Height="30" SelectionChanged="ltbox_SelectionChanged">
<ListBoxItem Content="选择..."></ListBoxItem>
<ListBoxItem Content="软件"></ListBoxItem>
<ListBoxItem Content="数学"></ListBoxItem>
</ListBox>
</Grid>
两个列表框中的项目相互异动,不太适合ItemsSource.Items.Add(_方式添加,可与i灵活添加或删除
事件:
SelectedChanged : 选择项类型,由绑定或添加时数据的类型决定
9、DataPicker 日期选择控件
控件:属于Control
<DatePicker HorizontalAlignment="Left" Margin="30,60,0,0" VerticalAlignment="Top" Width="369" Height="40"
DisplayDate="2020-02-01" DisplayDateStart="2020-01-01" DisplayDateEnd="2099-02-02">
</DatePicker>
自定义格式:自定义Style
<Grid>
<!--IsTodayHighted 默认为True ; IsDropDownOpen 默认为false ; FirstDayOfWeek默认为 Sunday;
DelectedDateFormat默认为:Short-->
<DatePicker Name="dpDate" HorizontalAlignment="Left" Margin="30,60,0,0" VerticalAlignment="Top" Width="100" Height="30"
DisplayDate="2020-02-01" DisplayDateStart="2020-01-01" DisplayDateEnd="2099-02-02" FirstDayOfWeek="Monday" SelectedDateFormat="Short"
SelectedDateChanged="dpDate_SelectedDateChanged">
<DatePicker.Resources>
<Style TargetType="DatePickerTextBox">
<Setter Property="BorderThickness" Value="0"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<TextBox x:Name="PART_TextBox" Text="{Binding Path=SelectedDate,StringFormat={}{0:yyyy-MM-dd},RelativeSource={RelativeSource
AncestorType={x:Type DatePicker}}}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DatePicker.Resources>
</DatePicker>
</Grid>
绑定:启动之后效果
事件:
SelectedDateChanged: 被选的日期改变
private void dpDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show(dpDate.Text);
MessageBox.Show(dpDate.SelectedDate.Value.ToString());
}
10、Canlendar日历
可以选择一个日期范围 属于: Control
属性:
可以选择多个日期范围,单个日期范围,显示范围 显示模式默认为Month
CalendarDayButtonStyle:
选中多个日期如何获取开始和结束日期:避免双击button才触发
private void cld_Date_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
{
stDate.Text = cld_Date.SelectedDates.First().ToShortDateString();
edDate.Text=cld_Date.SelectedDates.Last().ToShortDateString();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
txtSel.Text= cld_Date.SelectedDate.Value.ToString();
}
private void cld_Date_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
if (Mouse.Captured is CalendarItem)
{
Mouse.Capture(null); // 选中置空
}
}
CalendarItem 命名空间: System.Windows.Controls.Primitives;
<Grid>
<Calendar Name="cld_Date" HorizontalAlignment="Left" Margin="129,116,0,0" VerticalAlignment="Top" DisplayMode="Month" DisplayDateStart="2020-5-1" DisplayDateEnd="2999-5-1"
SelectionMode="MultipleRange" IsTodayHighlighted="True" SelectedDatesChanged="cld_Date_SelectedDatesChanged" PreviewMouseUp="cld_Date_PreviewMouseUp" >
</Calendar>
<TextBox Name="stDate" HorizontalAlignment="Left" Margin="162,68,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<TextBox Name="edDate" HorizontalAlignment="Left" Margin="400,68,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="400,200,0,0" VerticalAlignment="Top" Click="Button_Click"/>
<TextBox Name="txtSel" HorizontalAlignment="Left" Margin="578,140,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
</Grid>
事件:
SelectedDatesChanged: 日期为复数加s
当多选发生时候: 即SelectionMode="MultipleRange"
如何获取开始和结束日期:
11、slider滑块
TickFrequency:刻度之间的间隔
IsSnapToTickEnabled="True":
当更改某个 Thumb 位置并 IsSnapToTickEnabled 设置为 true
该属性时,会自动 Thumb 将该位置移动到最近的刻度线
Opacity: 透明度
Orientation: 方向;
Binding绑定的方式:
<Grid>
<Slider Name="Slider1" HorizontalAlignment="Left" Margin="106,132,0,0" VerticalAlignment="Top" Width="120" Maximum="100" Minimum="50" Orientation="Horizontal"
TickPlacement="Both" TickFrequency="2" Height="44" IsSnapToTickEnabled="True" SmallChange="5" LargeChange="10" IsDirectionReversed="True"
IsSelectionRangeEnabled="True" SelectionStart="20" SelectionEnd="50"/>
<Label Content="{Binding ElementName=Slider1,Path=Value,Mode=OneWay}" HorizontalAlignment="Left" Margin="330,163,0,0" VerticalAlignment="Top"/>
<TextBox Name="tb1" HorizontalAlignment="Left" Margin="166,252,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Height="27"
Text="Slider1" FontSize="{Binding ElementName=Slider1,Path=Value,Mode=OneWay}" Opacity="{Binding ElementName=Slider2,Path=Value,Mode=Default}"/>
<Slider Name="Slider2" HorizontalAlignment="Left" Margin="535,217,0,0" VerticalAlignment="Top" Width="120" Maximum="1" Minimum="0" Orientation="Horizontal"
TickPlacement="Both" TickFrequency="0.1" Height="44" IsSnapToTickEnabled="True" SmallChange="5" LargeChange="10" IsDirectionReversed="True"
IsSelectionRangeEnabled="True" SelectionStart="20" SelectionEnd="50"/>
</Grid>
12、ProcessBar进度条
属性:
IsIndeterminate: 不确定的,指示进度是显示实际值,true连续进度反馈
命名控件,using Windows.Controls.ProgressBar;
<Grid>
<PasswordBox HorizontalAlignment="Left" Margin="141,286,0,0" VerticalAlignment="Top" Width="120" Password="*"/>
<ProgressBar Name="pb1" HorizontalAlignment="Left" Height="10" Margin="235,177,0,0" VerticalAlignment="Top" Width="100" Orientation="Horizontal"
Minimum="0" Maximum="100" SmallChange="1" ValueChanged="pb1_ValueChanged"/>
<ProgressBar Name="pb2" HorizontalAlignment="Left" Height="143" Margin="563,217,0,0" VerticalAlignment="Top" Width="50" Orientation="Vertical"
RenderTransformOrigin="0.5,0.5" Minimum="0" Maximum="100" Value="0" IsIndeterminate="True"/>
<Button Name="bt1" Content="加载" HorizontalAlignment="Left" Margin="347,303,0,0" VerticalAlignment="Top" Click="bt1_Click"/>
<Label Name="lb1" Content="Label" HorizontalAlignment="Left" Margin="261,360,0,0" VerticalAlignment="Top"/>
</Grid>
代码:XAML中 pb1属性中不可设置Value属性,若要写如下代码:
public _09ProcessBarWindow()
{
InitializeComponent();
}
private void bt1_Click(object sender, RoutedEventArgs e)
{
double max = pb1.Maximum;
Task.Run(() =>
{
for (int i = 1; i <max; i++)
{
pb1.Dispatcher.Invoke(() =>
{
pb1.Value = i;
//lb1.Content = pb1.Value + "%";
});
Thread.Sleep(100);
}
});
}
private void pb1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
lb1.Content = e.NewValue ;
}
注释:
13、StackPanel
布局控件,类似Grid
属性:
Orientation=Horizontal 一行,一般设置VerticalAligment=Top Bottom Center Streth
vertical 一列,,HorizontalAligment=Left Right Center Streth
子元素超出部分,被隐藏,可嵌套
<Grid>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" FlowDirection="LeftToRight">
<Button Name="bt1" Width="30" Height="30"></Button>
<Button Margin="10,10,0,0">bt2</Button>
<Button>bt3</Button>
</StackPanel>
</Grid>
14、WrapPanel流面板
Orientation:子元素按照顺序排列,如果按照水平方向:从左到右,超出部分,自动换行到下一行;如果为垂直,从上到下,超出部分自动换行到下一列。
Orientation: ItemWidth ItemHeight
<Border BorderBrush="Red" BorderThickness="2" CornerRadius="5" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30,30,0,0" Width="300" Height="300">
<WrapPanel Name="wp1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="236" Height="248" ItemHeight="30" ItemWidth="30">
<Button>bt1</Button>
<Button>bt2</Button>
<Button>bt3</Button>
<Button>bt4</Button>
<Button>bt5</Button>
<Button>bt6</Button>
</WrapPanel>
</Border>
代码:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
for(int i = 0; i < 100; i++)
{
Button btn=new Button();
btn.Content= "btn"+i.ToString("00")+"号";
btn.Background=new SolidColorBrush(Colors.White);
btn.Name ="btn"+i.ToString();
btn.Margin=new Thickness(5,5,0,0);
wp1.Children.Add(btn);
}
}
15、DockPanel停靠面板
停靠面板: 顶部,左边,右边,,中间, Winform Dock:Top, left right, center
先添加的元素,有限占有权,所有子元素不会重叠,依次排列
与其他布局控件一起使用,
<Grid>
<!--<LastChildren 默认为true,最后的元素完全填充剩余的部分
如果在同一侧停靠多个,按照顺序依次排序>-->
<DockPanel LastChildFill="False" HorizontalAlignment="Left" Margin="0" VerticalAlignment="Top" Height="341" Width="477"
>
<StackPanel Width="50" Height="50" Background="LightBlue" DockPanel.Dock="Right"></StackPanel>
<StackPanel DockPanel.Dock="Left" Background="LightGreen" Height="30" Width="30"></StackPanel>
<StackPanel Width="100" Height="50" DockPanel.Dock="Left" Background="LightBlue">
<Label Content="left2"/>
</StackPanel>
<StackPanel Width="100" Height="50" DockPanel.Dock="Bottom" Background="LightBlue">
<Label Content="bottom"/>
</StackPanel>
<Grid Width="50" Height="50" Background="BlueViolet"/>
<Grid Background="Orange" Width="210" Height="123">
<DockPanel Margin="0,0,28,22">
<Button Content="top" Height="5" DockPanel.Dock="Top"></Button>
<Button Content="Left" Height="5" DockPanel.Dock="Left"></Button>
<Button Content="Right" Height="5" DockPanel.Dock="Right"></Button>
<Button Content="bottom" DockPanel.Dock="Bottom" Height="10"/>
</DockPanel>
</Grid>
</DockPanel>
</Grid>
事件:
16、Canvas画布
定义区域,子元素的显示位置,指定相对于
属性:
不能为子元素指定两个以上的附加属性,如果制定了,忽略后者;
当拆给你扣大小变化时,Canvas的尺寸随之变化,
重叠效果,优先显示:后添加的元素显示在上面,Panel.ZIndex相同,后添加显示在上边。
<Grid>
<Canvas Margin="55,0,484,150">
<Button Content="first" Width="30" Height="20" Canvas.Left="20" Canvas.Top="30" Canvas.Right="30" Canvas.Bottom="30"></Button>
<Button Content="second" Width="50" Height="20" Canvas.Left="30" Canvas.Bottom="30"></Button>
<Button Content="third" Width="30" Height="20" Canvas.Right="20" Canvas.Top="30"></Button>
<Button Content="fourth" Width="30" Height="20" Canvas.Right="20" Canvas.Bottom="30"></Button>
<Button Content="按钮1" Width="30" Height="20" Canvas.Right="20" Canvas.Top="30"></Button>
<Button Content="按钮2" Width="30" Height="20" Canvas.Left="50" Canvas.Top="100" RenderTransformOrigin="0.676,2.303" Panel.ZIndex="2"></Button>
<Button Content="按钮2" Width="30" Height="20" Canvas.Left="55" Canvas.Top="115" RenderTransformOrigin="0.676,2.303" Panel.ZIndex="1"></Button>
<Button Content="按钮2" Width="30" Height="20" Canvas.Left="60" Canvas.Top="130" RenderTransformOrigin="0.676,2.303" Panel.ZIndex="1"></Button>
</Canvas>
</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控件结合,
<Grid Height="400" Width="600" ShowGridLines="True" Background="BlueViolet">
<Grid.RowDefinitions>
<RowDefinition Height="53"></RowDefinition>
<RowDefinition/>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="53"></RowDefinition>
<RowDefinition Height="auto" MinHeight="15"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="1"></TextBox>
<TextBlock Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Background="LightGray"></TextBlock>
<Label Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" Background="YellowGreen" Content="用户信息:"></Label>
<Label Grid.Row="3" Grid.Column="1" Background="YellowGreen" Content="用信息:" Margin="20,10,26,0"/>
<Label Grid.Row="3" Grid.Column="1" Background="YellowGreen" Content="用信息123:" Margin="20,10,0,10"></Label>
<WrapPanel Grid.Column="1" Grid.Row="2" Background="SeaShell">
<Button Content="bt1" Height="25" Width="40"></Button>
<Button Content="bt1" Height="25" Width="40"></Button>
<Button Content="bt1" Height="25" Width="40"></Button>
<Button Content="bt1" Height="25" Width="40"></Button>
<Button Content="bt1" Height="25" Width="40"></Button>
</WrapPanel>
</Grid>
把Grid中的Height="400" Width="600"去掉,就可以自动方所。
18、GroupBox组框
分组容器控件:继承HeaderedContentControl,命名空间Control控件
分组,带标题,HeaderedContentControl带标题的内容空间
只有一个子元素作为它的内容 Content
属性::
循环嵌入:
<Grid>
<GroupBox Header="=导航菜单" Width="200" Height="200" Margin="0,0,552,218">
<StackPanel Orientation="Horizontal">
<Label Content="用户1"></Label>
<Label Content="用户2"></Label>
<Label Content="用户3"></Label>
<Label Content="用户4"></Label>
<Label Content="用户5"></Label>
</StackPanel>
</GroupBox>
<GroupBox Header="=导航菜单2" Width="200" Height="200" Margin="300,31,300,204">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Label Content="用户"></Label>
<TextBox Text="123456"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="用户"></Label>
<TextBox Text="123456"></TextBox>
</StackPanel>
</StackPanel>
</GroupBox>
</Grid>
public partial class _14GroupBoxWindow : Window
{
public _14GroupBoxWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
StackPanel spFirst = gp2.Content as StackPanel; // 为何内容为StackPanel
foreach(var ele in spFirst.Children)
{
StackPanel sp = ele as StackPanel;
foreach(var ele2 in sp.Children)
{
if(ele2 is TextBox)
{
TextBox tet = ele2 as TextBox;
string name = txtUserName.Text;
}
}
}
string name2= txtUserName.Text; // 直接通过name属性获取控件的Text
}
}
事件::
19、Expander扩展折叠控件
折叠控件,GroupBox 带标题,HeaderedContentControl
折叠或展开的特点,IsExpand 是否复合显示内容,ExpandDirection展开方向 Down Top/Left/Right。
GroupBox 不能折叠内容部分,Expander可以折叠,节省区域。
<Grid Margin="0,0,433,167">
<Expander>
<Grid RenderTransformOrigin="0.626,0.502">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
</Grid>
</Expander>
<Expander Header="用户权限" HorizontalAlignment="Left" Height="165" Margin="110,91,0,0" VerticalAlignment="Top" Width="auto"
Padding="10" ExpandDirection="Up" BorderThickness="2" RenderTransformOrigin="0.5,0.5" IsExpanded="False">
<Expander.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform AngleX="-0.576"/>
<RotateTransform/>
<TranslateTransform X="0.829"/>
</TransformGroup>
</Expander.RenderTransform>
<StackPanel Background="#FFE5E5E5">
<CheckBox Content="管理员"></CheckBox>
<CheckBox Content="系统管理员"></CheckBox>
</StackPanel>
</Expander>
</Grid>
20、TabControl选项卡控件
组件:多个共享相同的空间。
Selector ItemsControl:条目控件:ListBox, ComboBox:下拉框。
SelectedValue:SelectedItem、SelectedValuePath、Display
TabItem: 里边只能有一个StackPanel 不能有俩
选项卡项:TabItem---HeaderedContentControl Header。
SelectedContent Selected Item:TabItem对象。
TabItem: IsSelected 设置或者获取当前显示界面
<Grid>
<TabControl Name="tabCl" HorizontalAlignment="Left" Height="244" Margin="141,90,0,0" VerticalAlignment="Top" Width="398"
TabStripPlacement="Top">
<TabItem Header="用户信息" IsSelected="True">
<StackPanel Orientation="Vertical" Background="YellowGreen">
<StackPanel Orientation="Horizontal">
<Label Content="用户名"></Label>
<TextBox Text="admin" Width="100"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="=电话"></Label>
<TextBox Text="2233"></TextBox>
</StackPanel>
</StackPanel>
</TabItem>
<TabItem Header="角色信息">
<Grid Background="AliceBlue">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="29*"/>
<ColumnDefinition Width="61*"/>
<ColumnDefinition Width="302*"/>
</Grid.ColumnDefinitions>
</Grid>
</TabItem>
<TabItem Header="权限设置">
<Grid Background="AliceBlue"/>
</TabItem>
</TabControl>
<Button Name="bt1" Content="Button" HorizontalAlignment="Left" Margin="652,203,0,0" VerticalAlignment="Top" Click="bt1_Click"/>
</Grid>
private void bt1_Click(object sender, RoutedEventArgs e)
{
//tabCl.SelectedItem=tabCl.Items[1]; // 切换选项卡
if(tabCl.SelectedIndex <tabCl.Items.Count-1)
{
tabCl.SelectedIndex += 1;
}
else
{
tabCl.SelectedIndex = 0;
}
}
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。
<Grid>
<!-- 直接在Window中呈放一个Frame显示一个页面-->
<Frame Name="fm1" Content="Frame" HorizontalAlignment="Left" Height="257" Margin="100,49,0,0"
VerticalAlignment="Top" Width="562"></Frame>
<TabControl Name="tabCl" HorizontalAlignment="Left" Height="244" Margin="141,90,0,0" VerticalAlignment="Top" Width="398"
TabStripPlacement="Top">
<TabItem Header="用户信息" IsSelected="True">
<Frame Source="16_1PageRolePage.xaml" NavigationUIVisibility="Visible"></Frame>
</TabItem>
<TabItem Header="角色信息" IsSelected="True">
<Frame Source="16_1PageRolePage.xaml" NavigationUIVisibility="Visible"></Frame>
</TabItem>
<TabItem Header="权限设置">
<Grid Background="AliceBlue"/>
</TabItem>
</TabControl>
</Grid>
代码:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// 1、直接在xaml代码中设置Source
// 2、frame.Source= new Uri("", UriKind.Relative);
// fm1.Source = new Uri("16_1PageRolePage.xaml",UriKind.Relative); // 相对路径
//3 、先实例化Page对象
_16_1PageRolePage pageRoleInfo= new _16_1PageRolePage();
fm1.Navigate(pageRoleInfo);
}
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 。
上面有复选框
<Grid>
<ListView HorizontalAlignment="Left" Height="239" VerticalAlignment="Top" Width="564">
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.Header>
<CheckBox Name="ckAll" Content="全选"></CheckBox>
</GridViewColumn.Header>
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="chk" Tag=" {Binding UserId" IsChecked="{Binding ElementName=chkAll,Path=IsChecked,Mode=OneWay}"></CheckBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="编号" DisplayMemberBinding="{Binding UserId}" Width="50"></GridViewColumn>
<GridViewColumn Header="账号" Width="70">
<GridViewColumn.CellTemplate>
<DataTemplate>
<!--<Label Content="{Binding UserName}" Foreground="BlueViolet"></Label>-->
<TextBlock Text="{Binding UserName}" Foreground="YellowGreen" HorizontalAlignment="Left"
TextAlignment="Center"></TextBlock>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="状态" DisplayMemberBinding="{Binding UserState}">
</GridViewColumn>
<GridViewColumn Header="部门编号" DisplayMemberBinding="{Binding Depth}"></GridViewColumn>
<GridViewColumn Header="年龄" DisplayMemberBinding="{Binding UserAge}" Width="50">
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
代码:
private List<UserInfo> GetUserList1()
{
List<UserInfo> list = new List<UserInfo>();
string sql = "select UserId,UserName,UserState,UserAge from UserInfos Where Depth>0"; // 数据库语句
SqlDataReader dr = SqlHelper.ExecuteReader(sql,1);
while(dr.Read())
{
UserInfo user = new UserInfo();
user.UserId = (int)dr["UserId"];
user.UserName = (string)dr["UserName"];
user.UserState = (int)dr["UserState"];
user.UserAge = (int)dr["UserAge"];
user.Depth = (int)dr["Depth"];
list.Add(user);
}
dr.Close();
return list;
}
}
public class UserInfo
{
public int UserId { get; set; }
public string UserName { get; set; }
public int UserState { get; set; }
public int UserAge { get; set; }
public int Depth { get; set; }
}
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:
<Grid>
<!--<DataGrid HeadersVisibility="Row" AutoGenerateColumns="False"
AlternatingRowBackground="Yellow" CanUserAddRows="True" IsReadOnly="True"
VerticalScrollBarVisibility="Visible">
</DataGrid>-->
<DataGrid Name="dgList" HeadersVisibility="All" AutoGenerateColumns="False"
AlternatingRowBackground="Yellow" CanUserAddRows="True" IsReadOnly="True"
VerticalScrollBarVisibility="Visible" AlternationCount="2" GridLinesVisibility="Horizontal" SelectionUnit="Cell"
SelectionMode="Single" RowHeaderWidth="20" ItemsSource="{Binding UserList2}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="Transparent"></Setter>
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="LightGray"></Setter>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="LightBlue"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="编号" Binding="{Binding UserId}" Width="50"></DataGridTextColumn>
<DataGridTextColumn Header="姓名" Binding="{Binding UserName}" Width="80">
<DataGridTextColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Foreground="Red"></TextBlock>
</DataTemplate>
</DataGridTextColumn.HeaderTemplate>
<!--<默认为文本框 DataGridTextColumn.EditingElementStyle>
<Style TargetType="TextBox"></Style>
</DataGridTextColumn.EditingElementStyle>-->
</DataGridTextColumn>
<DataGridCheckBoxColumn Header="状态" Binding="{Binding UserState}"></DataGridCheckBoxColumn>
<DataGridComboBoxColumn x:Name="colDepth" Header="部门" SelectedValueBinding="{Binding DepthId}" Width="100"
DisplayMemberPath=" DeptName" SelectedValuePath="DepthId"
ItemsSource="{Binding DeptList2,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding DataContext.DeptList,RelativeSource={RelativeSource
Mode=FindAncestor,AncestorType=Window}}"></Setter>
</Style>
</DataGridComboBoxColumn.ElementStyle>
</DataGridComboBoxColumn>
<DataGridTemplateColumn Header="年龄" Width="60">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Label Content="{Binding UserAge}" Foreground="Green" Background="LightBlue"></Label>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<!--内容可更改-->
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding UserName}"></TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
24、Menu
简介:Windows菜单控件,控件可用于按层次组织与命令和事件处理程序关联的元素。
常用属性:IsMainMenu 是否接收菜单激活通知 True 按alt 或f10激活 如果为false。
MenuItem介绍 :Menu 控件中的可选项,, 带标题的条目控件。
父类: HeaderedItemsControl
CommandParameter Icon Header
InputGestureText:
InputGestureText="Ctrl+R" 快捷键
Click事件:
打开角色管理界面
页面.show();
Command命令:
<Window.Resources>
<!-- 定义命令 -->
<RoutedUICommand x:Key="cmdRole"/>
<RoutedUICommand x:Key="cmdUser"/>
</Window.Resources>
<!--输入绑定 Key Mouse-->
<Window.InputBindings>
<KeyBinding Command="{StaticResource cmdRole}" Gesture="Ctrl+R"></KeyBinding>
</Window.InputBindings>
<!-- 将命令与处理程序关联起来 -->
<Window.CommandBindings>
<CommandBinding Command="{StaticResource cmdRole}" Executed="miRole_Click"/>
<CommandBinding Command="{StaticResource cmdUser}" Executed="miUser_Click"/>
</Window.CommandBindings>
<Grid>
<Menu Height="30" VerticalAlignment="Top" IsMainMenu="False">
<MenuItem Header="系统管理">
<!--Command="{StaticResource cmdRole}"-->
<MenuItem Name="miRole" Header="角色管理" Command="{StaticResource cmdRole}"
InputGestureText="Ctrl+R">
<MenuItem.Icon>
<Image Source="image/12window.png"></Image>
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="用户管理" Command="{StaticResource cmdUser}"></MenuItem>
<MenuItem Header="菜单管理"></MenuItem>
<MenuItem Header="权限管理"></MenuItem>
<MenuItem Header="角色"></MenuItem>
</MenuItem>
<MenuItem Header="基础资料">
<MenuItem Header="商品管理">
<MenuItem Header="商品类别"></MenuItem>
<MenuItem Header="商品名称"></MenuItem>
</MenuItem>
<MenuItem Header="仓库管理"></MenuItem>
<MenuItem Header="单位管理"></MenuItem>
<MenuItem Header="入库设置"></MenuItem>
</MenuItem>
<MenuItem Header="业务管理"></MenuItem>
<MenuItem Header="查询中心">
<MenuItem Header="查询姓名"></MenuItem>
<MenuItem Header="查询资料"></MenuItem>
<MenuItem Header="查询性别"></MenuItem>
<MenuItem Header="查询年龄"></MenuItem>
</MenuItem>
</Menu>
</Grid>
控件使用(一个
25、动态生成菜单项
动态生成菜单项:递归加载菜单数据、分层数据模板;
获取菜单数据:按层次结构组织的数据列表。
菜单模型: 编号,名称 父类单编号 快捷键
菜单项模型:百年好 名称 快捷键 子菜单列表
数据模板:分层数据模板 HeaderedItemsControl Menu TreeView
HierarchicalDataTemplate(分层数据模板):支持HeaderedItemsCOntrol的数据绑定,就是定义分层数据的模板,一般应用在MenuItem或TreeViewItem。
父类:DataTemplate
属性: ItemsSource 数据模板的绑定 ItemTemplate以指示如何显示数据层次结构中的下一个界别中的项目 ItemContainerStyle应用与每个子项的项容器 AlternationCount交替项的子项目的容器的数量。
<Window.Resources>
<RoutedUICommand x:Key="cmdUser"></RoutedUICommand>
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource cmdUser}" Executed="CommandBinding_Executed"></CommandBinding>
</Window.CommandBindings>
<Grid>
<Menu HorizontalAlignment="Left" Height="30" Margin="0" VerticalAlignment="Top" BorderBrush="LightBlue"
BorderThickness="1" ItemsSource="{Binding MenuList}">
<Menu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="InputGestureText" Value="{Binding MKey}"></Setter>
<Setter Property="InputGestureText" Value="{Binding MKey1}"></Setter>
</Style>
</Menu.ItemContainerStyle>
<Menu.ItemTemplate>
<HierarchicalDataTemplate>
<TextBlock Text="{Binding MenuName}" VerticalAlignment="Center"></TextBlock>
</HierarchicalDataTemplate>
</Menu.ItemTemplate>
</Menu>
</Grid>
26、ContextMenu文本菜单
右键出现如下:
父类:MenuBase MenuItem (HeaderedItemsControl) ItemsControl 特定于某个元素之上的功能菜单。右键菜单,上下文菜单。
属性:HorizontalOffset verticalOffset 右键菜单控件相对于带年纪位置的水平、垂直Label(右键菜单的目标元素)
快捷键相应:与命令或事件处理程序关联起来。
应用:不独立,依赖于某个元素
<Grid>
<Label Content="用户管理" HorizontalAlignment="Left" Margin="184,97,0,0"
VerticalAlignment="Top" Height="33" Width="73" BorderBrush="Blue" BorderThickness="1">
<Label.ContextMenu>
<ContextMenu HorizontalOffset="10" VerticalAlignment="Top">
<MenuItem Header="打开页面"></MenuItem>
<MenuItem Header="操作">
<MenuItem Header="赋值"></MenuItem>
<MenuItem Header="剪切"></MenuItem>
</MenuItem>
</ContextMenu>
</Label.ContextMenu>
</Label>
</Grid>
27、TreeView树视图
属性介绍:树形控件
TreeView 父类: ItemsControl -- 条目控件
MenuItem: 派生于HeaderedItemsControl
按层次结构组织数据
SelectedValue选择项的值
SelectedValuePath 菜单名称 编号 (列名或属性名)
TreeViewItem被选中触发
private void tv1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
var val = e.NewValue as TreeViewItem;
MessageBox.Show(val.Header.ToString());
}
private void tv1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
var val = e.NewValue as TreeViewItem;
MessageBox.Show(val.Header.ToString());
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
TreeViewItem tv = new TreeViewItem();
tv.Header= "进销存系统";
tv1.Items.Add(tv);
TreeViewItem tv2 = new TreeViewItem();
tv2.Header = "用户管理";
tv1.Items.Add(tv2);
TreeViewItem tv3 = new TreeViewItem();
tv3.Header = "角色信息";
tv1.Items.Add(tv3);
}
进销存系统 系统管理 用户管理
动态模板:
<Window.Resources>
<RoutedUICommand x:Key="cmdUser"></RoutedUICommand>
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource cmdUser}" Executed="CommandBinding_Executed"></CommandBinding>
</Window.CommandBindings>
<Grid>
<TreeView Name="tvList" HorizontalAlignment="Left" Height="30" Margin="0" VerticalAlignment="Top" BorderBrush="LightBlue"
BorderThickness="1">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type model:MenuItemModel}" ItemsSource="{Binding SubItems}">
<TextBlock Text="{Binding MenuName}" VerticalAlignment="Center"></TextBlock>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
27、ToolBar工具条
Orientation 指示排列方向
Band BandIndex
TollBarTray
代码:
<Grid>
<ToolBar HorizontalAlignment="Left" Height="36" Margin="10,10,0,0" Width="695"
IsOverflowOpen="True">
<Button Content="新建"></Button>
<Separator/>
<Image Source="image/12window.png" Width="20" Height="20"></Image>
<CheckBox Content="是否保存" IsChecked="True" Margin="10,0"></CheckBox>
<Separator/>
<RadioButton Name="rbRed1" ToolTip="Red" Command="{StaticResource setColor}">
<RadioButton.Content>
<Rectangle Width="10" Height="10" Fill="Red"></Rectangle>
</RadioButton.Content>
</RadioButton>
<RadioButton ToolTip="Yellow" Command="{StaticResource setColor}">
<RadioButton.Content>
<Rectangle Width="10" Height="10" Fill="Yellow"></Rectangle>
</RadioButton.Content>
</RadioButton>
<!--<RadioButton></RadioButton>-->
<Separator/>
<ComboBoxItem Content="选择" VerticalAlignment="Center"
PreviewMouseLeftButtonDown="ComboBoxItem_MouseLeftButtonDown"></ComboBoxItem>
</ToolBar>
<Label Name="lb1" Content="我是测试文本" Margin="103,78,0,0" VerticalAlignment="Top"></Label>
</Grid>
IsOverFlowOpen:
如果溢出区可见,则为 true
;否则为 false
。
ToolBarTray:
<Window.Resources>
<RoutedUICommand x:Key="setColor"></RoutedUICommand>
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource setColor}" Executed="setColor_Executed"></CommandBinding>
</Window.CommandBindings>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0*"/>
<ColumnDefinition Width="0*"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ToolBarTray Orientation="Horizontal" Grid.ColumnSpan="3">
<ToolBar HorizontalAlignment="Left" Height="36" Margin="10,10,0,0" Width="695"
IsOverflowOpen="True" Band="0" BandIndex="0">
<Button Content="新建"></Button>
<Separator/>
<Image Source="image/12window.png" Width="20" Height="20"></Image>
<CheckBox Content="是否保存" IsChecked="True" Margin="10,0"></CheckBox>
<Separator/>
<RadioButton Name="rbRed1" ToolTip="Red" Command="{StaticResource setColor}">
<RadioButton.Content>
<Rectangle Width="10" Height="10" Fill="Red"></Rectangle>
</RadioButton.Content>
</RadioButton>
<RadioButton ToolTip="Yellow" Command="{StaticResource setColor}">
<RadioButton.Content>
<Rectangle Width="10" Height="10" Fill="Yellow"></Rectangle>
</RadioButton.Content>
</RadioButton>
<!--<RadioButton></RadioButton>-->
<Separator/>
<ComboBoxItem Content="选择" VerticalAlignment="Center"
PreviewMouseLeftButtonDown="ComboBoxItem_MouseLeftButtonDown"></ComboBoxItem>
</ToolBar>
<!--<Label Name="lb1" Content="我是测试文本" Margin="103,78,0,0" VerticalAlignment="Top"></Label>-->
<ToolBar HorizontalAlignment="Left" Height="36" VerticalAlignment="Top"
IsOverflowOpen="True" Band="0" BandIndex="1">
<Button Content="复制"></Button>
<Button Content="剪切"></Button>
</ToolBar>
</ToolBarTray>
</Grid>
29、statusBar状态栏
StatusBar: 应用程序窗体中的水平栏中显示项和信息的kongj (状态栏)。
父类:ItemsControl。
项:StatusBarItem StatusBar中的项。
进度过程:
简单的状态栏:登录者 当前时间 版权信息 进度。
<Grid>
<StatusBar HorizontalAlignment="Left" VerticalAlignment="Stretch" Height="30">
<StatusBarItem Content="登陆者"></StatusBarItem>
<StatusBarItem>
<StackPanel Orientation="Horizontal">
<Label Content="当前时间"></Label>
<TextBlock Text="2020-02-01"></TextBlock>
<!--StatusBarItem中内容控件只能有一个<TextBlock Text="2020-02-01"></TextBlock>-->
</StackPanel>
</StatusBarItem>
<StatusBarItem>
<StackPanel Orientation="Horizontal">
<Label Content="加载进度"></Label>
<ProgressBar Name="pbar" Value="0" Width="100" Height="25">
<ProgressBar.Triggers>
<EventTrigger RoutedEvent="ProgressBar.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation From="0" To="{Binding ElementName=pbar,Path=Maximum}" Storyboard.TargetName="pbar"
Storyboard.TargetProperty="Value"
Duration="0:0:5"></DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ProgressBar.Triggers>
</ProgressBar>
</StackPanel>
</StatusBarItem>
</StatusBar>
</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加绝对路径,否则无法播放
<Window x:Class="WpfAppTest.MediaElementWindow"
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:WpfAppTest"
mc:Ignorable="d"
Title="MediaElementWindow" Height="450" Width="800">
<Grid>
<Border BorderThickness="2" BorderBrush="YellowGreen" HorizontalAlignment="Left" Height="275" Margin="43,26,0,0" VerticalAlignment="Top" Width="583">
<MediaElement Source="绝对路径/medias/tongyao1.mp4" IsMuted="False" Volume="0.3" SpeedRatio="1" UnloadedBehavior="Stop" Balance="-0.6" StretchDirection="Both" Stretch="Fill" />
</Border>
</Grid>
</Window>
<Grid>
<!--<Border BorderThickness="2" BorderBrush="Yellow" HorizontalAlignment="Left" Height="234"
Margin="112,70,0,0" VerticalAlignment="Top" Width="512">
--><!--<MediaElement Source="image/play123.mp4" IsMuted="False"
UnloadedBehavior="Stop">
</MediaElement>--><!--
<MediaElement Name="me1" Source="/media/play123.mp4" LoadedBehavior="Manual" UnloadedBehavior="Stop" Stretch="Fill" Margin="29,0,63,27"/>
</Border>-->
<MediaElement x:Name="mediaElement" Source="play123.mp4" LoadedBehavior="Manual" Width="400" Height="225"
MediaOpened="mediaElement_MediaOpened" MediaFailed="mediaElement_MediaFailed"/>
<Button Content="Play" HorizontalAlignment="Left" Margin="444,12,0,0" VerticalAlignment="Top" Width="75"
Click="Button_Click" />
</Grid>
代码:
private void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
{
mediaElement.Source = new Uri("E:\\SoftStudy\\C#\\C#\\基础\\01WPF基础\\02控件_1\\image\\play123.mp4", UriKind.Relative);
mediaElement.Play();
}
private void mediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
MessageBox.Show("Media failed to load: " + e.ErrorException.Message);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//if (mediaElement.SetCurrentValue == MediaState.Paused || mediaElement.CurrentState == MediaState.Stopped)
//{
// mediaElement.Play();
//}
//else
//{
// mediaElement.Pause();
//}
mediaElement.Source = new Uri("E:\\SoftStudy\\C#\\C#\\基础\\01WPF基础\\02控件_1\\image\\play123.mp4", UriKind.Absolute);
mediaElement.Play();
}
播放器案例:
记载时,创建一个计时器,播放位置调整、时间文本更新
打开: 选择播放数据源,加载完毕,自动播放。
播放或暂停-
停止:回到原来位置,停止播放。
快进:前进10s 后退:10s
OpenFileDialog ofd = new OpenFileDialog();
打开文件对话框,
参考:2021-08-14 WPF控件专题 MediaElement 控件详解_qq61972345e36b7的技术博客_51CTO博客
控件案例 别忘记Loaded
<Window x:Class="WpfAppTest.MediaElementWindow2"
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:WpfAppTest"
mc:Ignorable="d"
Title="MediaElementWindow2" Height="450" Width="800" Loaded="Window_Loaded">
<Window.Resources>
<Style x:Key="btnStyle" TargetType="Button">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Offset="0" Color="White"/>
<GradientStop Offset="0.444" Color="#FF53897A"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="FontStyle" Value="Oblique"/>
<Setter Property="Margin" Value="5"/>
<Setter Property="Width" Value="60"/>
<Setter Property="Foreground" Value="Gold"/>
<Style.Triggers>
<Trigger Property="Button.IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Black"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<StackPanel>
<Border Background="Black" BorderThickness="3" HorizontalAlignment="Center" Height="300" VerticalAlignment="Top" Width="500">
<Border.Effect>
<DropShadowEffect Color="#FFE4CC8D"/>
</Border.Effect>
<Border.BorderBrush>
<LinearGradientBrush StartPoint="1,0" EndPoint="1,1">
<GradientStop Offset="0" Color="White"/>
<GradientStop Offset="0.5" Color="Gold"/>
</LinearGradientBrush>
</Border.BorderBrush>
<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" />
</Border>
<StackPanel Margin="0,10,0,0" Orientation="Horizontal" HorizontalAlignment="Center">
<TextBlock Text="播放进度" Foreground="Gold" Margin="5"/>
<Slider x:Name="posSlider" Minimum="0" Width="190" Value="{Binding ElementName=me,Path=Position}" IsMoveToPointEnabled="True" PreviewMouseLeftButtonUp="PosSlider_PreviewMouseLeftButtonUp" />
<TextBlock Text="音量" Foreground="Gold" Margin="20,0,0,0"/>
<Slider x:Name="volumeSlider" Margin="10,0" Minimum="0" Maximum="1" Value="0.5" Width="167" />
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,10">
<Button x:Name="openBtn" Content="打开" Style="{StaticResource btnStyle}" Click="OpenBtn_Click"
/>
<Button x:Name="playBtn" Content="播放" Style="{StaticResource btnStyle}" Click="PlayBtn_Click"
/>
<Button x:Name="stopBtn" Content="停止" Style="{StaticResource btnStyle}" Click="StopBtn_Click"
/>
<Button x:Name="backBtn" Content="快退" Style="{StaticResource btnStyle}" Click="BackBtn_Click"
/>
<Button x:Name="forwardBtn" Content="快进" Style="{StaticResource btnStyle}" Click="ForwardBtn_Click"
/>
<Label Name="lblTime" Width="100" Height="30" Content="00:04"></Label>
</StackPanel>
</StackPanel>
</Grid>
</Window>
主程序代码:
System.Timers.Timer timer = null;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += Timer_Elapsed;
}
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//子线程执行
this.Dispatcher.Invoke(new Action(() =>
{
//主线程
posSlider.Value = me.Position.TotalSeconds;
SetTime();
}
));
}
/// <summary>
/// 设置时间文本框的值
/// </summary>
private void SetTime()
{
lblTime.Content = string.Format("{0:00}:{1:00}:{2:00}", me.Position.Hours, me.Position.Minutes, me.Position.Seconds);
}
//选择播放文件
private void OpenBtn_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = @"视频文件(*.avi格式)|*.avi|视频文件(*.wav格式)|*.wav|视频文件(*.wmv格式)|*.wmv|视频文件(*.mp4格式)|*.mp4|All Files|*.*";
if (ofd.ShowDialog() == false)
{
return;
}
string filePath = "";
filePath = ofd.FileName;
if (filePath == "")
return;
//设置媒体源
me.Source = new Uri(filePath, UriKind.Absolute);
playBtn.IsEnabled = true;
me.Play();
timer.Start();
playBtn.Content = "暂停";
}
//播放或暂停
private void PlayBtn_Click(object sender, RoutedEventArgs e)
{
SetPlayer(true);
PlayPause();
}
/// <summary>
/// 播放或暂停
/// </summary>
private void PlayPause()
{
if (playBtn.Content.ToString() == "播放")
{
me.Play();
timer.Start();
playBtn.Content = "暂停";
me.ToolTip = "单击暂停";
}
else
{
me.Pause();
timer.Stop();
playBtn.Content = "播放";
me.ToolTip = "单击播放";
SetTime();
}
}
/// <summary>
/// 设置操作按钮的可用状态
/// </summary>
/// <param name="bl"></param>
private void SetPlayer(bool bl)
{
stopBtn.IsEnabled = bl;
playBtn.IsEnabled = bl;
backBtn.IsEnabled = bl;
forwardBtn.IsEnabled = bl;
}
/// <summary>
/// 停止
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StopBtn_Click(object sender, RoutedEventArgs e)
{
me.Stop();
posSlider.Value = 0;
lblTime.Content = "0:0:0";
playBtn.Content = "播放";
timer.Stop();
}
/// <summary>
/// 快进 当前播放位置前进10s
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ForwardBtn_Click(object sender, RoutedEventArgs e)
{
me.Pause();
timer.Stop();
me.Position = me.Position + TimeSpan.FromSeconds(10);
SetTime();
me.Play();
timer.Start();
}
/// <summary>
/// 快退
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BackBtn_Click(object sender, RoutedEventArgs e)
{
me.Pause();
timer.Stop();
me.Position = me.Position - TimeSpan.FromSeconds(10);
SetTime();
me.Play();
timer.Start();
}
private void Me_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
PlayPause();
}
/// <summary>
/// 媒体加载完毕后
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Me_MediaOpened(object sender, RoutedEventArgs e)
{
posSlider.Maximum = me.NaturalDuration.TimeSpan.TotalSeconds;
lblTime.Content = "0:0:0";
SetPlayer(true);
}
/// <summary>
///拖动播放进度
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PosSlider_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
me.Pause();
timer.Stop();
int val = (int)posSlider.Value;
me.Position = new TimeSpan(0, 0, 0, val);
SetTime();
me.Play();
timer.Start();
}
private void Me_MediaEnded(object sender, RoutedEventArgs e)
{
MessageBox.Show("播放结束");
timer.Stop();
}
30、RichTextBox超文本
Document 获取或设置RichTextBox的System.Window.Documents.FlowDocument
属性:
FlowDocument:
inline Run Hyperlink
block paragraph section blockuicontainer
FlowDocument:
Block Paragraph Run Section Hyperlink InlineUIContainer BlockUIContainer
<Grid>
<RichTextBox Name="rtbContent" HorizontalAlignment="Left" Height="229" Margin="70,70,0,0"
VerticalAlignment="Top" Width="400" IsDocumentEnabled="True">
<FlowDocument>
<Paragraph TextIndent="24">
<Run Text="RichTextBox"></Run>
</Paragraph>
<Paragraph>
<Run Text="RichTextBox"></Run>
<Hyperlink Click="Hyperlink_Click">百度一下</Hyperlink>
</Paragraph>
<Paragraph>
<Run Text="另一个文本"></Run>
</Paragraph>
<Section></Section>
</FlowDocument>
</RichTextBox>
<Button Content="获取内容" Margin="547,88,188,323" Height="30"/>
</Grid>
代码:
private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
Process proc=new Process();
proc.StartInfo.FileName = "http://www.baidu.com";
proc.Start();
}
private void GetText_Click(object sender, RoutedEventArgs e)
{
TextRange range = new TextRange(rtbContent.Document.ContentStart,rtbContent.Document.ContentEnd);
string contentText = range.Text; // 纯文本内容
MessageBox.Show(contentText);
}