Академический Документы
Профессиональный Документы
Культура Документы
Otras versiones
continuar. Aceptar o Cancelar. Aceptar se indica que el usuario ha introducido los datos y desea
que la funcin contine su proceso con esos datos. Cancelar indica que el usuario desea detener la
ejecucin de la funcin.
no modal, por otra parte, no impide que el usuario active otras ventanas mientras est abierto.
Cerrar para cerrar el cuadro de dilogo y puede proporcionar botones adicionales para ejecutar
funciones concretas, como un botn Buscar siguiente para buscar la palabra siguiente que
coincida con los criterios de una bsqueda de palabra.
Dialog Box Sample proporciona ejemplos relacionados.
Este tema contiene las secciones siguientes.
Cuadros de mensaje
Cuadros de dilogo comunes
Cuadros de dilogo personalizados
Temas relacionados
Cuadros de mensaje
cuadro de mensaje es un cuadro de dilogo que se puede utilizar para mostrar informacin textual
y permitirles que los usuarios tomen decisiones con botones.
MessageBox. MessageBox permite configurar el texto, el ttulo, el icono y los botones del cuadro
de mensaje, utilizando cdigo como el siguiente.
C#
VB
// Configure the message box to be displayed
string messageBoxText = "Do you want to save changes?";
string caption = "Word Processor";
MessageBoxButton button = MessageBoxButton.YesNoCancel;
MessageBoxImage icon = MessageBoxImage.Warning;
C#
VB
C#
VB
// Display message box
MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button,
icon);
// Process message box results
switch (result)
{
case MessageBoxResult.Yes:
// User pressed Yes button
// ...
break;
case MessageBoxResult.No:
// User pressed No button
// ...
break;
case MessageBoxResult.Cancel:
// User pressed Cancel button
// ...
break;
}
C#
VB
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
}
Microsoft.Win32.OpenFileDialog.
Nota
OpenFileDialog se puede utilizar para recuperar sin ningn riesgo los nombres de archivo por
aplicaciones que se ejecutan con confianza parcial (vea Seguridad (WPF)).
C#
VB
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
}
Microsoft.Win32.SaveFileDialog.
C#
VB
// Configure printer dialog box
System.Windows.Controls.PrintDialog dlg = new
System.Windows.Controls.PrintDialog();
dlg.PageRangeSelection = PageRangeSelection.AllPages;
dlg.UserPageRangeEnabled = true;
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Print document
}
cuadro de dilogo Margins como ejemplo (vea Dialog Box Sample). Margins se muestra en la
figura siguiente.
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.MarginsDialogBox"
xmlns:local="clr-namespace:SDKSample"
Title="Margins"
Height="190"
Width="300"
MinHeight="10"
MinWidth="300"
ResizeMode="CanResizeWithGrip"
ShowInTaskbar="False"
WindowStartupLocation="CenterOwner"
FocusManager.FocusedElement="{Binding ElementName=leftMarginTextBox}">
<Grid>
...
<!-- Accept or Cancel -->
<StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="4">
VB
Imports System.Windows ' Window, RoutedEventArgs, IInputElement,
DependencyObject
Imports System.Windows.Controls ' Validation
Imports System.Windows.Input ' Keyboard
Namespace SDKSample
Public Class MarginsDialogBox
Inherits Window
Public Sub New()
Me.InitializeComponent()
End Sub
...
End Class
End Namespace
C#
using System.Windows; // Window, RoutedEventArgs, IInputElement,
DependencyObject
using System.Windows.Controls; // Validation
using System.Windows.Input; // Keyboard
namespace SDKSample
{
public partial class MarginsDialogBox : Window
{
public MarginsDialogBox()
{
InitializeComponent();
}
...
}
}
XAML
<!--Main Window-->
...
<MenuItem Name="formatMarginsMenuItem" Header="_Margins..."
Click="formatMarginsMenuItem_Click" />
C#
VB
using
using
using
using
using
System; // EventArgs
System.ComponentModel; // CancelEventArgs
System.Windows; // Window, MessageBoxXxx, RoutedEventArgs
System.Windows.Controls; // TextChangedEventArgs
Microsoft.Win32; // OpenFileDialog
namespace SDKSample
{
public partial class MainWindow : Window
{
...
void formatMarginsMenuItem_Click(object sender, RoutedEventArgs e)
{
// Instantiate the dialog box
MarginsDialogBox dlg = new MarginsDialogBox();
// Configure the dialog box
dlg.Owner = this;
dlg.DocumentMargin = this.documentTextBox.Margin;
...
}
...
}
}
Window.Owner con una referencia a la ventana que est mostrando el cuadro de dilogo.
Informacin general sobre ventanas de WPF para obtener ms informacin).
Nota
Informacin general sobre UI Automation) debe proporcionar un propietario.
ShowDialog.
C#
VB
using System.Globalization;
using System.Windows.Controls;
namespace SDKSample
{
public class MarginValidationRule : ValidationRule
{
double minMargin;
double maxMargin;
public double MinMargin
{
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.MarginsDialogBox"
xmlns:local="clr-namespace:SDKSample"
Title="Margins"
Height="190"
Width="300"
MinHeight="10"
MinWidth="300"
ResizeMode="CanResizeWithGrip"
ShowInTaskbar="False"
WindowStartupLocation="CenterOwner"
FocusManager.FocusedElement="{Binding ElementName=leftMarginTextBox}">
<Grid>
...
<Label Grid.Column="0" Grid.Row="0">Left Margin:</Label>
<TextBox Name="leftMarginTextBox" Grid.Column="1" Grid.Row="0">
<TextBox.Text>
<Binding Path="Left" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:MarginValidationRule MinMargin="0" MaxMargin="10" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
...
</Window>
C#
VB
using System.Windows; // Window, RoutedEventArgs, IInputElement,
DependencyObject
using System.Windows.Controls; // Validation
using System.Windows.Input; // Keyboard
namespace SDKSample
{
public partial class MarginsDialogBox : Window
{
...
void okButton_Click(object sender, RoutedEventArgs e)
{
// Don't accept the dialog box if there is invalid data
if (!IsValid(this)) return;
...
}
// Validate all dependency objects in a window
bool IsValid(DependencyObject node)
{
// Check if dependency object was passed
if (node != null)
{
// Check if dependency object is valid.
// NOTE: Validation.GetHasError works for controls that have
validation rules attached
bool isValid = !Validation.GetHasError(node);
if (!isValid)
{
// If the dependency object is invalid, and it can receive
the focus,
// set the focus
if (node is IInputElement)
Keyboard.Focus((IInputElement)node);
return false;
}
}
// If this dependency object is valid, check all child dependency
objects
immediately,
}
}
// All dependency objects are valid
return true;
GetHasError, el control no vlido obtiene el foco, el mtodo IsValid devuelve false y la ventana
se considera no vlida.
C#
VB
using System.Windows; // Window, RoutedEventArgs, IInputElement,
DependencyObject
using System.Windows.Controls; // Validation
using System.Windows.Input; // Keyboard
namespace SDKSample
{
public partial class MarginsDialogBox : Window
{
...
void cancelButton_Click(object sender, RoutedEventArgs e)
{
// Dialog box canceled
this.DialogResult = false;
}
...
IsCancel de un botn se establece en true y el usuario presiona el botn Cancelar o la tecla ESC,
DialogResult se establece automticamente en false. Click.
XAML
<Button Name="cancelButton" IsCancel="True">Cancel</Button>
false cuando un usuario presiona el botn Cerrar de la barra de ttulo o elige el elemento de men
Cerrar en el men Sistema.
C#
VB
using
using
using
using
using
System; // EventArgs
System.ComponentModel; // CancelEventArgs
System.Windows; // Window, MessageBoxXxx, RoutedEventArgs
System.Windows.Controls; // TextChangedEventArgs
Microsoft.Win32; // OpenFileDialog
namespace SDKSample
{
public partial class MainWindow : Window
{
...
void formatMarginsMenuItem_Click(object sender, RoutedEventArgs e)
{
...
...
}
true, la funcin lo utiliza como indicacin para recuperar y procesar los datos proporcionados por
el usuario.
Nota
ShowDialog, no se puede volver a abrir el cuadro de dilogo.
false, la funcin debe finalizar el procesamiento correctamente.
XAML
<!--Main Window-->
VB
Imports
Imports
Imports
Imports
Imports
Namespace SDKSample
Public Class MainWindow
Inherits Window
...
Private Sub editFindMenuItem_Click(ByVal sender As Object, ByVal e As
RoutedEventArgs)
Dim dlg As New FindDialogBox(Me.documentTextBox)
dlg.Owner = Me
AddHandler dlg.TextFound, New TextFoundEventHandler(AddressOf
Me.dlg_TextFound)
dlg.Show()
End Sub
...
End Class
End Namespace
C#
using
using
using
using
using
System; // EventArgs
System.ComponentModel; // CancelEventArgs
System.Windows; // Window, MessageBoxXxx, RoutedEventArgs
System.Windows.Controls; // TextChangedEventArgs
Microsoft.Win32; // OpenFileDialog
namespace SDKSample
{
public partial class MainWindow : Window
{
...
void editFindMenuItem_Click(object sender, RoutedEventArgs e)
{
// Instantiate the dialog box
FindDialogBox dlg = new FindDialogBox(this.documentTextBox);
// Configure the dialog box
dlg.Owner = this;
dlg.TextFound += new TextFoundEventHandler(dlg_TextFound);
// Open the dialog box modally
dlg.Show();
}
...
C#
VB
using System;
namespace SDKSample
{
public delegate void TextFoundEventHandler(object sender, EventArgs e);
}
C#
VB
using
using
using
using
System; // EventArgs
System.Windows; // Window, MessageBoxXxx, RoutedEventArgs
System.Windows.Controls; // TextBox, TextChangedEventArgs
System.Text.RegularExpressions; // Regex
namespace SDKSample
{
public partial class FindDialogBox : Window
{
public event TextFoundEventHandler TextFound;
protected virtual void OnTextFound()
{
TextFoundEventHandler textFound = this.TextFound;
if (textFound != null) textFound(this, EventArgs.Empty);
}
...
C#
VB
using
using
using
using
System; // EventArgs
System.Windows; // Window, MessageBoxXxx, RoutedEventArgs
System.Windows.Controls; // TextBox, TextChangedEventArgs
System.Text.RegularExpressions; // Regex
namespace SDKSample
{
public partial class FindDialogBox : Window
{
...
void findNextButton_Click(object sender, RoutedEventArgs e)
{
...
// Text found
this.index = match.Index;
this.length = match.Length;
OnTextFound();
...
}
...
}
}
C#
VB
using System; // EventArgs
using System.ComponentModel; // CancelEventArgs
using System.Windows; // Window, MessageBoxXxx, RoutedEventArgs
}
}
C#
VB
using
using
using
using
System; // EventArgs
System.Windows; // Window, MessageBoxXxx, RoutedEventArgs
System.Windows.Controls; // TextBox, TextChangedEventArgs
System.Text.RegularExpressions; // Regex
namespace SDKSample
{
public partial class FindDialogBox : Window
{
...
Vea tambin
Conceptos
Informacin general sobre el control Popup
Otros recursos
Dialog Box Sample
ColorPicker Custom Control Sample