实现弹窗
弹窗和前面实现的登录跳转的功能类似,都是定义一个窗口类,在其它窗口的函数中实例化使用。区别在于,登录跳转实例化新的窗体后,登录的窗体就丢弃了,保留新建的窗体;而弹窗则是一个临时性窗体,完成当前的工作后就丢弃了,原有窗体保留。
第一步,新建wpf窗口,命名为LabelPopupWindow.xaml
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-p6QP0YeJ-1612920616680)(F:\chenggeng\Blog\Image\wpf基础开发img3.png)]
第二步,自定义弹窗布局、功能及样式,LabelPopupWindow.xaml内容如下:
<Window x:Class="wpfbase.LabelPopupWindow"
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:wpfbase"
mc:Ignorable="d"
WindowStartupLocation="CenterOwner"
Title="Label" Height="200" Width="200">
<StackPanel Margin="20 10 20 5" Orientation="Vertical">
<TextBox Name="label" TextAlignment="Left">
<TextBox.Text>
<Binding ElementName="labelzoo" Path="SelectedItem.Content"/>
</TextBox.Text>
</TextBox>
<ListBox Name="labelzoo" Height="100" Width="155" HorizontalAlignment="Left" >
<ListBoxItem>Orange</ListBoxItem>
<ListBoxItem>Green</ListBoxItem>
<ListBoxItem>Blue</ListBoxItem>
<ListBoxItem>Gray</ListBoxItem>
<ListBoxItem>LightGray</ListBoxItem>
<ListBoxItem>Red</ListBoxItem>
<ListBoxItem>dog</ListBoxItem>
</ListBox>
<DockPanel>
<Button Content="取消" DockPanel.Dock="Left" Width="50" Height="25" Click="LabelESC" Margin="5"/>
<Button Content="确定" DockPanel.Dock="Right" Width="50" Height="25" Click="LabelOK" Margin="5"/>
<TextBlock Text=""/>
</DockPanel>
</StackPanel>
</Window>
第三步,LabelPopupWindow.xaml.cs内容如下:
using System.Windows;
namespace wpfbase
{
public partial class LabelPopupWindow : Window
{
public LabelPopupWindow()
{
InitializeComponent();
}
// 取消按钮响应
private void LabelESC(object sender, RoutedEventArgs e) {
this.DialogResult = false;
}
// 确定按钮响应
private void LabelOK(object sender, RoutedEventArgs e) {
this.DialogResult = true;
}
}
}
窗口采用ShowDialog显示时:1.新建的窗体不关闭,原有窗体会挂起;2.对窗体的DialogResult参数赋值后(false,true),窗体自动关闭,DialogResult的值通过ShowDialog函数返回给父窗体。
第四步,主窗体调用弹窗。
...
namespace wpfbase
{
...
private void PopupLabel(object sender, RoutedEventArgs e) {
LabelPopupWindow labelpopupwindow = new LabelPopupWindow();
labelpopupwindow.Left = 500;
labelpopupwindow.Top = 500;
bool? result = labelpopupwindow.ShowDialog();
if(result == true) {
Console.WriteLine(labelpopupwindow.label.Text);
}
}
}
}