您现在的位置是:首页 > 正文

WPF笔记汇总之消息框与界面控件

2024-02-01 04:11:01阅读 1

WPF消息框与界面控件

接上一篇 《WPF笔记汇总之命令的使用》,这篇主要汇总WPF中的消息框及通用界面控件如工具栏,菜单栏,状态栏等控件的使用方法汇总。

1. 消息框的使用

消息框就是提示用的,可以带标题,带图标,带多种选择的确定按钮,也可以返回用户的选择,返回的就是MessageBoxResult枚举中的值。

<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
	<StackPanel.Resources>
		<Style TargetType="Button">
			<Setter Property="Margin" Value="0,0,0,10" />
		</Style>
	</StackPanel.Resources>
	<Button Name="btnSimpleMessageBox" Click="btnSimpleMessageBox_Click">Simple MessageBox</Button>
	<Button Name="btnMessageBoxWithTitle" Click="btnMessageBoxWithTitle_Click">MessageBox with title</Button>
	<Button Name="btnMessageBoxWithButtons" Click="btnMessageBoxWithButtons_Click">MessageBox with buttons</Button>
	<Button Name="btnMessageBoxWithResponse" Click="btnMessageBoxWithResponse_Click">MessageBox with response</Button>
	<Button Name="btnMessageBoxWithIcon" Click="btnMessageBoxWithIcon_Click">MessageBox with icon</Button>
	<Button Name="btnMessageBoxWithDefaultChoice" Click="btnMessageBoxWithDefaultChoice_Click">MessageBox with default choice</Button>
</StackPanel>
private void btnSimpleMessageBox_Click(object sender, RoutedEventArgs e)
{
	MessageBox.Show("Hello, world!");
}

private void btnMessageBoxWithTitle_Click(object sender, RoutedEventArgs e)
{
	MessageBox.Show("Hello, world!", "My App");
}

private void btnMessageBoxWithButtons_Click(object sender, RoutedEventArgs e)
{
	MessageBox.Show("This MessageBox has extra options.\n\nHello, world?", "My App", MessageBoxButton.YesNoCancel);
}

private void btnMessageBoxWithResponse_Click(object sender, RoutedEventArgs e)
{
	MessageBoxResult result = MessageBox.Show("Would you like to greet the world with a \"Hello, world\"?", "My App", MessageBoxButton.YesNoCancel);
	switch (result)
	{
		case MessageBoxResult.Yes:
			MessageBox.Show("Hello to you too!", "My App");
			break;
		case MessageBoxResult.No:
			MessageBox.Show("Oh well, too bad!", "My App");
			break;
		case MessageBoxResult.Cancel:
			MessageBox.Show("Nevermind then...", "My App");
			break;
	}
}

private void btnMessageBoxWithIcon_Click(object sender, RoutedEventArgs e)
{
	MessageBox.Show("Hello, world!", "My App", MessageBoxButton.OK, MessageBoxImage.Information);
}

private void btnMessageBoxWithDefaultChoice_Click(object sender, RoutedEventArgs e)
{
	MessageBox.Show("Hello, world?", "My App", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
}

2. 对话框使用

2.1 打开文件
<WrapPanel HorizontalAlignment="Center" DockPanel.Dock="Top" Margin="0,0,0,10">
	<Button Name="btnOpenFile" Click="btnOpenFile_Click">Open file</Button>
</WrapPanel>
<TextBox Name="txtEditor" />
OpenFileDialog openFileDialog = new OpenFileDialog();
//openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.Filter = "Image files (*.png;*.jpeg)|*.png;*.jpeg|All files (*.*)|*.*";
// openFileDialog.InitialDirectory = @"d:\";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
if (openFileDialog.ShowDialog() == true)
	txtEditor.Text = File.ReadAllText(openFileDialog.FileName);

OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (openFileDialog.ShowDialog() == true)
{
	foreach (string filename in openFileDialog.FileNames)
		lbFiles.Items.Add(Path.GetFileName(filename));
}
2.2 保存文件
<DockPanel Margin="10">
	<WrapPanel HorizontalAlignment="Center" DockPanel.Dock="Top" Margin="0,0,0,10">
		<Button Name="btnSaveFile" Click="btnSaveFile_Click">Save file</Button>
	</WrapPanel>
	<TextBox Name="txtEditor" TextWrapping="Wrap" AcceptsReturn="True" ScrollViewer.VerticalScrollBarVisibility="Auto" />
</DockPanel>
private void btnSaveFile_Click(object sender, RoutedEventArgs e)
{
	SaveFileDialog saveFileDialog = new SaveFileDialog();
	saveFileDialog.Filter = "Text file (*.txt)|*.txt|C# file (*.cs)|*.cs";
	saveFileDialog.InitialDirectory = @"D:\temp\";
	saveFileDialog.Title = "WPF学习";
	if (saveFileDialog.ShowDialog() == true)
		File.WriteAllText(saveFileDialog.FileName, txtEditor.Text);
}
2.3 自定义对话框

类似新建一个窗体,然后调用这个窗体就行了

<Window x:Class="WpfStudy.MyInputDialogs"
        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:WpfStudy"
        mc:Ignorable="d"
        Title="MyInputDialogs" Height="150" Width="390" 
		ContentRendered="Window_ContentRendered" WindowStartupLocation="CenterScreen">
	<Grid Margin="15">
		<Grid.ColumnDefinitions>
			<ColumnDefinition Width="Auto" />
			<ColumnDefinition Width="*" />
		</Grid.ColumnDefinitions>
		<Grid.RowDefinitions>
			<RowDefinition Height="Auto" />
			<RowDefinition Height="Auto" />
			<RowDefinition Height="Auto" />
		</Grid.RowDefinitions>

		<Image Source="/me.png" Width="32" Height="32" Grid.RowSpan="2" Margin="20,0" />

		<Label Name="lblQuestion" Grid.Column="1">Question:</Label>
		<TextBox Name="txtAnswer" Grid.Column="1" Grid.Row="1" MinWidth="250">Answer</TextBox>

		<WrapPanel Grid.Row="2" Grid.ColumnSpan="2" HorizontalAlignment="Right" Margin="0,15,0,0">
			<Button IsDefault="True" Name="btnDialogOk" Click="btnDialogOk_Click" MinWidth="60" Margin="0,0,10,0">_Ok</Button>
			<Button IsCancel="True" MinWidth="60">_Cancel</Button>
		</WrapPanel>
	</Grid>
</Window>

public partial class MyInputDialogs : Window
{
	public MyInputDialogs(string question, string defaultAnswer = "")
	{
		InitializeComponent();
		lblQuestion.Content = question;
		txtAnswer.Text = defaultAnswer;
	}

	private void btnDialogOk_Click(object sender, RoutedEventArgs e)
	{
		this.DialogResult = true;
	}

	private void Window_ContentRendered(object sender, EventArgs e)
	{
		txtAnswer.SelectAll();
		txtAnswer.Focus();
	}

	public string Answer
	{
		get { return txtAnswer.Text; }
	}
}

使用自定义输入窗体

MyInputDialogs inputDialog = new MyInputDialogs("Please enter your name:", "John Doe");
if (inputDialog.ShowDialog() == true)
	lblName.Text = inputDialog.Answer;

3. 通用界面控件

3.1 菜单控件

<Window.CommandBindings>
	<CommandBinding Command="New" CanExecute="NewCommand_CanExecute" Executed="NewCommand_Executed" />
</Window.CommandBindings>

<StackPanel>
	<!--普通菜单-->
	<DockPanel>
		<Menu DockPanel.Dock="Top">
			<MenuItem Header="_File">
				<MenuItem Header="_New" Command="New"/>
				<MenuItem Header="_Open" />
				<MenuItem Header="_Save" />
				<Separator />
				<MenuItem Header="_Exit" />
			</MenuItem>
		</Menu>
		<TextBox AcceptsReturn="True" />
	</DockPanel>
	<!--图标和复选框菜单-->
	<DockPanel>
		<Menu DockPanel.Dock="Top">
			<MenuItem Header="_File">
				<MenuItem Header="_Exit" />
			</MenuItem>
			<MenuItem Header="_Tools">
				<MenuItem Header="_Manage users">
					<MenuItem.Icon>
						<Image Source="/images/file.png" />
					</MenuItem.Icon>
				</MenuItem>
				<MenuItem Header="_Show groups" IsCheckable="True" IsChecked="True" />
			</MenuItem>
		</Menu>
		<TextBox AcceptsReturn="True" />
	</DockPanel>
	<!--系统命令菜单-->
	<DockPanel>
		<Menu DockPanel.Dock="Top">
			<MenuItem Header="_File">
				<MenuItem Command="New" />
				<Separator />
				<MenuItem Header="_Exit" />
			</MenuItem>
			<MenuItem Header="_Edit">
				<MenuItem Command="Cut" />
				<MenuItem Command="Copy" />
				<MenuItem Command="Paste" />
			</MenuItem>
		</Menu>
		<TextBox AcceptsReturn="True" Name="txtEditor" />
	</DockPanel>
</StackPanel>
3.2 上下文菜单

上下文菜单就是,右键某个控件或者窗体的时候,弹出的菜单。

<!--普通上下文菜单-->
	<Button Content="Right-click me!" VerticalAlignment="Center" HorizontalAlignment="Center">
		<Button.ContextMenu>
			<ContextMenu>
				<MenuItem Header="Menu item 1" />
				<MenuItem Header="Menu item 2" />
				<Separator />
				<MenuItem Header="Menu item 3" />
			</ContextMenu>
		</Button.ContextMenu>
	</Button>
<!--带命令和图标的菜单-->
<TextBox Text="Right-click here for context menu!">
	<TextBox.ContextMenu>
		<ContextMenu>
			<MenuItem Command="Cut">
				<MenuItem.Icon>
					<Image Source="/images/file.png" />
				</MenuItem.Icon>
			</MenuItem>
			<MenuItem Command="Copy">
				<MenuItem.Icon>
					<Image Source="/images/file.png" />
				</MenuItem.Icon>
			</MenuItem>
			<MenuItem Command="Paste">
				<MenuItem.Icon>
					<Image Source="/images/file.png" />
				</MenuItem.Icon>
			</MenuItem>
		</ContextMenu>
	</TextBox.ContextMenu>
</TextBox>

还可以用后置代码设置菜单

<Window.Resources>
	<ContextMenu x:Key="cmButton">
		<MenuItem Header="Menu item 1" />
		<MenuItem Header="Menu item 2" />
		<Separator />
		<MenuItem Header="Menu item 3" />
	</ContextMenu>
</Window.Resources>

<Grid>
	<Button Content="Click me!" VerticalAlignment="Center" HorizontalAlignment="Center" Click="Button_Click" />
</Grid>
private void Button_Click(object sender, RoutedEventArgs e)
{
	ContextMenu cm = this.FindResource("cmButton") as ContextMenu;
	cm.PlacementTarget = sender as Button;
	cm.IsOpen = true;
}
3.3 工具栏控件

工具栏简单的说就是一个条状容器面板上放置几个控件,其中有几个重要的概念:溢出,溢出就是没有足够的空间显示工具栏上的所有按钮,WPF会将它们放入一个菜单,该菜单能通过单击工具栏右侧的箭头来访问。附加属性ToolBar.OverflowMode就是用来设置溢出方式的。 默认值为IfNeeded,工具栏项将放在溢出菜单中。 您可以使用始终Always或从不来Never替代默认值,就是始终将项目放在溢出菜单中或阻止项目移动到溢出菜单。
还有一个就是工具栏的放置位置,工具栏也可以位于应用程序窗口的底部,甚至可以在两侧。 WPF工具栏支持所有这些功能。工具栏置地就是简单地将工具栏与面板底部对接,而不是顶部。垂直工具栏需要使用工具栏托盘的Orientation属性。

<Window.CommandBindings>
	<CommandBinding Command="New" CanExecute="CommonCommandBinding_CanExecute" />
	<CommandBinding Command="Open" CanExecute="CommonCommandBinding_CanExecute" />
	<CommandBinding Command="Save" CanExecute="CommonCommandBinding_CanExecute" />
</Window.CommandBindings>
<StackPanel>
	
	<DockPanel>
	<!--简单工具栏-->
	<ToolBarTray DockPanel.Dock="Top">
		<ToolBar>
			<Button Command="New" Content="New" />
			<Button Command="Open" Content="Open" />
			<Button Command="Save" Content="Save" />
		</ToolBar>
		<ToolBar>
			<Button Command="Cut" Content="Cut" />
			<Button Command="Copy" Content="Copy" />
			<Button Command="Paste" Content="Paste" />
		</ToolBar>
	</ToolBarTray>
	<TextBox AcceptsReturn="True" />
		<!--图文工具栏-->
		<ToolBarTray DockPanel.Dock="Right" Orientation="Vertical" >
		<ToolBar>
			<Button Command="Cut" ToolTip="Cut selection to Windows Clipboard.">
				<Image Source="/images/file.png" />
			</Button>
			<Button Command="Copy" ToolTip="Copy selection to Windows Clipboard.">
				<Image Source="/images/file.png" />
			</Button>
			<Button Command="Paste" ToolTip="Paste from Windows Clipboard.">
				<StackPanel Orientation="Horizontal">
					<Image Source="/images/file.png" />
					<TextBlock Margin="3,0,0,0">Paste</TextBlock>
				</StackPanel>
			</Button>
		</ToolBar>
	</ToolBarTray>
		<TextBox AcceptsReturn="True" />
	</DockPanel>
	
	<!--溢出演示-->
	<DockPanel>
		<ToolBar DockPanel.Dock="Top" >
			<Button Command="Cut" Content="Cut" ToolBar.OverflowMode="Always" />
			<Button Command="Copy" Content="Copy" ToolBar.OverflowMode="AsNeeded" />
			<Button Command="Paste" Content="Paste" ToolBar.OverflowMode="Never" />
		</ToolBar>
	</DockPanel>
	
	<!--自定义工具栏-->
	<DockPanel>
		<ToolBarTray DockPanel.Dock="Top">
			<ToolBar>
				<Button Command="Cut" ToolTip="Cut selection to Windows Clipboard.">
					<Image Source="/images/file.png" />
				</Button>
				<Button Command="Copy" ToolTip="Copy selection to Windows Clipboard.">
					<Image Source="/images/file.png" />
				</Button>
				<Button Command="Paste" ToolTip="Paste from Windows Clipboard.">
					<StackPanel Orientation="Horizontal">
						<Image Source="/images/file.png" />
						<TextBlock Margin="3,0,0,0">Paste</TextBlock>
					</StackPanel>
				</Button>
				<Separator />
				<Label>Font size:</Label>
				<ComboBox>
					<ComboBoxItem>10</ComboBoxItem>
					<ComboBoxItem IsSelected="True">12</ComboBoxItem>
					<ComboBoxItem>14</ComboBoxItem>
					<ComboBoxItem>16</ComboBoxItem>
				</ComboBox>
			</ToolBar>
		</ToolBarTray>
		<TextBox AcceptsReturn="True" />
	</DockPanel>
</StackPanel>
3.4 状态栏控件

状态栏用于显示有关应用程序当前状态的各种信息,如光标位置,字数,任务进度等。

<StackPanel>
	<TextBox AcceptsReturn="True" Name="txtEditor" SelectionChanged="txtEditor_SelectionChanged" Height="100"/>
	<!--简单用法-->
	<DockPanel>
		<StatusBar DockPanel.Dock="Bottom">
			<StatusBarItem>
				<TextBlock Name="lblCursorPosition" />
			</StatusBarItem>
		</StatusBar>
	</DockPanel>
	<TextBlock></TextBlock>
	<!--高级用法-->
	<DockPanel>
		<StatusBar DockPanel.Dock="Bottom">
			<StatusBar.ItemsPanel>
				<ItemsPanelTemplate>
					<Grid>
						<Grid.ColumnDefinitions>
							<ColumnDefinition Width="100" />
							<ColumnDefinition Width="Auto" />
							<ColumnDefinition Width="*" />
							<ColumnDefinition Width="Auto" />
							<ColumnDefinition Width="100" />
						</Grid.ColumnDefinitions>
					</Grid>
				</ItemsPanelTemplate>
			</StatusBar.ItemsPanel>
			<StatusBarItem>
				<TextBlock Name="lblCursorPosition2" />
			</StatusBarItem>
			<Separator Grid.Column="1" />
			<StatusBarItem Grid.Column="2">
				<TextBlock Text="c:\path\of\current\file.txt" />
			</StatusBarItem>
			<Separator Grid.Column="3" />
			<StatusBarItem Grid.Column="4">
				<ProgressBar Value="50" Width="90" Height="16" />
			</StatusBarItem>
		</StatusBar>
		</DockPanel>
</StackPanel>
private void txtEditor_SelectionChanged(object sender, RoutedEventArgs e)
{
	int row = txtEditor.GetLineIndexFromCharacterIndex(txtEditor.CaretIndex);
	int col = txtEditor.CaretIndex - txtEditor.GetCharacterIndexFromLineIndex(row);
	lblCursorPosition.Text = "Line " + (row + 1) + ", Char " + (col + 1);
	lblCursorPosition2.Text = "Line " + (row + 1) + ", Char " + (col + 1);
}

网站文章

  • 计算机excel怎么备注,excel自动得出结果_excel表格怎么让计算公式得出结果并带有备注?_excel得出结果_excel怎么得出结果...

    计算机excel怎么备注,excel自动得出结果_excel表格怎么让计算公式得出结果并带有备注?_excel得出结果_excel怎么得出结果...

    excel表格怎么让计算公式得出结果并带有备注?在建筑行业里造价人员经常要用到excel表进行计算公式,但是很多人不知道如何使计算公式得出结果并带有备注,下面我来手把手讲解1、打开excel表,ctr...

    2024-02-01 04:10:36
  • 【HAOI2016】找相同字符

    后缀自动机入门题分别对两个串建后缀自动机,然后把endpos的大小算出来,最后在两个后缀自动机上一起dfs一遍并且算答案。#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>using namespace std;const int max...

    2024-02-01 04:10:29
  • SQLSERVER 查看sql执行状态,死锁等待

    SELECT [Spid] = session_Id, ecid, [Database] = DB_NAME(sp.dbid), [User] = nt_username, [Status] ...

    2024-02-01 04:10:22
  • 深入 Java 调试体系,第 4 部分: Java 调试接口(JDI)

    深入 Java 调试体系,第 4 部分: Java 调试接口(JDI)

    JDI 简介JDI(Java Debug Interface)是 JPDA 三层模块中最高层的接口,定义了调试器(Debugger)所需要的一些调试接口。基于这些接口,调试器可以及时地了解目标虚拟机的状态,例如查看目标虚拟机上有哪些类和实例等。另外,调试者还可以控制目标虚拟机的执行,例如挂起和恢复目标虚拟机上的线程,设置断点等。目前,大多数的 JDI 实现都是通过 Java 语言编

    2024-02-01 04:09:52
  • 基于javaweb+mysql的jsp+servlet个人博客系统(java+jsp+servlet+mysql) 最新发布

    基于javaweb+mysql的jsp+servlet个人博客系统(java+jsp+servlet+mysql) 最新发布

    基于javaweb+mysql的jsp+servlet个人博客系统(java+jsp+servlet+mysql)基于javaweb+mysql的JSP+Servlet个人博客系统(java+jsp+servlet+mysql)eclipse/idea/myeclipse/sts等均可配置运行。课程设计,大作业,毕业设计,项目练习,学习演示等。

    2024-02-01 04:09:44
  • 温故而知新!月薪20k+的Java面试都问些什么?BAT大厂面试总结

    温故而知新!月薪20k+的Java面试都问些什么?BAT大厂面试总结

    前言 现如今的互联网应用大都是采用 分布式系统架构 设计的,所以 消息队列 已经逐渐成为企业的应用系统 内部通信 的核心手段, 它具有 低耦合、可靠投递、广播、流量控制、最终一致性 等一系列功能。 当...

    2024-02-01 04:09:36
  • 访问差异类型的集合类--visitor模式入门

    访问差异类型的集合类--visitor模式入门

    一,问题提出访问同一类型的集合类是我们最常见的事情了,我们工作中这样的代码太常见了。1  Iterator ie  =  list.iterator();2  while (ie.hasNext()) {3     Person p  =  (Person)ie.next();4     p.doWork();5 }这种访问的特点是集合类中的对象是同一类对象Person,他们拥...

    2024-02-01 04:09:10
  • “第五空间”wp-misc-run

    “第五空间”wp-misc-run

    第一次正式比赛二血。小开心。下载下来是一个run.exe。运行一下没反应…看图表是个docx,7zip打开,果然嵌了一个docx。打开,查十六进制等等基本操作,没发现有什么东西。回去运行分离出来的ex...

    2024-02-01 04:09:02
  • Flask实现CSRF保护

    Flask实现CSRF保护

    参考官方文档 CSRF跨站请求伪造,源于WEB的隐式身份验证机制,WEB的身份验证机制虽然可以抱着一个请求时来自于某个用户的浏览器,但却无法保证该请求是用户批准发送的。 例如,用户登录受信任的网址A,在本地生成了Cookie,在Cookie没有失效的情况下去访问了危险网站B,B可能会盗用你的身份,以你的名义去发送恶意请求,邮件,盗取你的账号,设置购买商品,造成你个人隐私泄露,已经财产安...

    2024-02-01 04:08:55
  • 修改git tag的描述信息

    修改git tag的描述信息

    修改git tag的描述信息message

    2024-02-01 04:08:50