WebView Class

Proporciona un control que hospeda el contenido HTML en una aplicación.

Herencia

Object
  DependencyObject
    UIElement
      FrameworkElement
        WebView

Sintaxis


public sealed class WebView : FrameworkElement

Atributos

[MarshalingBehavior(Agile)]
[Threading(Both)]
[Version(0x06020000)]
[WebHostHidden()]

Members

A continuación se indican los tipos de miembros de WebView (Clase):

Constructores

A continuación se indican los constructores de WebView (Clase).

ConstructorDescripción
WebView Initializes a new instance of the WebView class.

 

Eventos

A continuación se indican los eventos de WebView (Clase).

EventoDescripción
ContentLoading Occurs when the WebView has started loading new content.
DataContextChanged Occurs when the value of the FrameworkElement.DataContext property changes. (Se hereda de FrameworkElement)
DOMContentLoaded Occurs when the WebView has finished parsing the current HTML content.
DoubleTapped (not supported; see Remarks) Occurs when an otherwise unhandled DoubleTap interaction occurs over the hit test area of this element. (Se hereda de UIElement)
DragEnter (not supported; see Remarks) Occurs when the input system reports an underlying drag event with this element as the target. (Se hereda de UIElement)
DragLeave (not supported; see Remarks) Occurs when the input system reports an underlying drag event with this element as the origin. (Se hereda de UIElement)
DragOver (not supported; see Remarks) Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Se hereda de UIElement)
Drop (not supported; see Remarks) Occurs when the input system reports an underlying drop event with this element as the drop target. (Se hereda de UIElement)
FrameContentLoading Occurs when a frame in the WebView has started loading new content.
FrameDOMContentLoaded Occurs when a frame in the WebView has finished parsing its current HTML content.
FrameNavigationCompleted Occurs when a frame in the WebView has finished loading its content.
FrameNavigationStarting Occurs before a frame in the WebView navigates to new content.
GotFocus Occurs when a UIElement receives focus. (Se hereda de UIElement)
Holding (not supported; see Remarks) Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Se hereda de UIElement)
KeyDown (not supported; see Remarks) Occurs when a keyboard key is pressed while the UIElement has focus. (Se hereda de UIElement)
KeyUp (not supported; see Remarks) Occurs when a keyboard key is released while the UIElement has focus. (Se hereda de UIElement)
LayoutUpdated Occurs when the layout of the visual tree changes, due to layout-relevant properties changing value or some other action that refreshes the layout. (Se hereda de FrameworkElement)
LoadCompleted Occurs when top-level navigation completes and the content loads into the WebView control or when an error occurs during loading.
Loaded Occurs when a FrameworkElement has been constructed and added to the object tree, and is ready for interaction. (Se hereda de FrameworkElement)
LongRunningScriptDetected Occurs periodically while the WebView executes JavaScript, letting you halt the script.
LostFocus Occurs when a UIElement loses focus. (Se hereda de UIElement)
ManipulationCompleted (not supported; see Remarks) Occurs when a manipulation on the UIElement is complete. (Se hereda de UIElement)
ManipulationDelta (not supported; see Remarks) Occurs when the input device changes position during a manipulation. (Se hereda de UIElement)
ManipulationInertiaStarting (not supported; see Remarks) Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins. (Se hereda de UIElement)
ManipulationStarted (not supported; see Remarks) Occurs when an input device begins a manipulation on the UIElement. (Se hereda de UIElement)
ManipulationStarting (not supported; see Remarks) Occurs when the manipulation processor is first created. (Se hereda de UIElement)
NavigationCompleted Occurs when the WebView has finished loading the current content or if navigation has failed.
NavigationFailed Occurs when the WebView cannot complete the navigation attempt.
NavigationStarting Occurs before the WebView navigates to new content.
PointerCanceled (not supported; see Remarks) Occurs when a pointer that made contact abnormally loses contact. (Se hereda de UIElement)
PointerCaptureLost (not supported; see Remarks) Occurs when pointer capture previously held by this element moves to another element or elsewhere. (Se hereda de UIElement)
PointerEntered (not supported; see Remarks) Occurs when a pointer enters the hit test area of this element. (Se hereda de UIElement)
PointerExited (not supported; see Remarks) Occurs when a pointer leaves the hit test area of this element. (Se hereda de UIElement)
PointerMoved (not supported; see Remarks) Occurs when a pointer moves while the pointer remains within the hit test area of this element. (Se hereda de UIElement)
PointerPressed (not supported; see Remarks) Occurs when the pointer device initiates a Press action within this element. (Se hereda de UIElement)
PointerReleased (not supported; see Remarks) Occurs when the pointer device that previously initiated a Press action is released, while within this element. (Se hereda de UIElement)
PointerWheelChanged (not supported; see Remarks) Occurs when the delta value of a pointer wheel changes. (Se hereda de UIElement)
RightTapped (not supported; see Remarks) Occurs when a right-tap input stimulus happens while the pointer is over the element. (Se hereda de UIElement)
ScriptNotify Occurs when the content contained in the WebView control passes a string to the application by using JavaScript.
SizeChanged Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Se hereda de FrameworkElement)
Tapped (not supported; see Remarks) Occurs when an otherwise unhandled Tap interaction occurs over the hit test area of this element. (Se hereda de UIElement)
Unloaded Occurs when this object is no longer connected to the main object tree. (Se hereda de FrameworkElement)
UnsafeContentWarningDisplaying Occurs when the WebView shows a warning page for content that was reported as unsafe by SmartScreen Filter.
UnviewableContentIdentified Occurs when the WebView attempts to download an unsupported file.

 

Métodos

The WebView Clase tiene estos métodos. También hereda métodos de Object Clase.

MétodoDescripción
AddHandler Adds a routed event handler for a specified routed event, adding the handler to the handler collection on the current element. Specify handledEventsToo as true to have the provided handler be invoked even if the event is handled elsewhere. (Se hereda de UIElement)
Arrange Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Se hereda de UIElement)
ArrangeOverride Provides the behavior for the Arrange pass of layout. Classes can override this method to define their own Arrange pass behavior. (Se hereda de FrameworkElement)
BuildLocalStreamUri Creates a URI that you can pass to NavigateToLocalStreamUri.
CancelDirectManipulations Cancels ongoing direct manipulation processing (system-defined panning/zooming) on any ScrollViewer parent that contains the current UIElement. (Se hereda de UIElement)
CapturePointer Sets pointer capture to a UIElement. Once captured, only the element that has capture will fire pointer-related events. (Se hereda de UIElement)
CapturePreviewToStreamAsync Creates an image of the current WebView contents and writes it to the specified stream.
CaptureSelectedContentToDataPackageAsync Asynchronously gets a DataPackage that contains the selected content within the WebView.
ClearValue Clears the local value of a dependency property. (Se hereda de DependencyObject)
FindName Retrieves an object that has the specified identifier name. (Se hereda de FrameworkElement)
FindSubElementsForTouchTargeting Enables a UIElement subclass to expose child elements that assist with resolving touch targeting. (Se hereda de UIElement)
Focus Sets the input focus to the WebView.
GetAnimationBaseValue Returns any base value established for a dependency property, which would apply in cases where an animation is not active. (Se hereda de DependencyObject)
GetBindingExpression Returns the BindingExpression that represents the binding on the specified property. (Se hereda de FrameworkElement)
GetValue Returns the current effective value of a dependency property from a DependencyObject. (Se hereda de DependencyObject)
GoBack Navigates the WebView to the previous page in the navigation history.
GoForward Navigates the WebView to the next page in the navigation history.
GoToElementStateCore When implemented in a derived class, enables per-state construction of a visual tree for a control template in code, rather than by loading XAML for all states at control startup. (Se hereda de FrameworkElement)
InvalidateArrange Invalidates the arrange state (layout) for a UIElement. After the invalidation, the UIElement will have its layout updated, which will occur asynchronously. (Se hereda de UIElement)
InvalidateMeasure Invalidates the measurement state (layout) for a UIElement. (Se hereda de UIElement)
InvokeScript Executes the specified script function from the currently loaded HTML, with specific arguments.
InvokeScriptAsync As an asynchronous action, executes the specified script function from the currently loaded HTML, with specific arguments.
Measure Updates the DesiredSize of a UIElement. Typically, objects that implement custom layout for their layout children call this method from their own MeasureOverride implementations to form a recursive layout update. (Se hereda de UIElement)
MeasureOverride Provides the behavior for the Measure pass of the layout cycle. Classes can override this method to define their own Measure pass behavior. (Se hereda de FrameworkElement)
Navigate Loads the HTML content at the specified Uniform Resource Identifier (URI).
NavigateToLocalStreamUri Loads local web content at the specified URI using an IUriToStreamResolver.
NavigateToString Loads the specified HTML content as a new document.
NavigateWithHttpRequestMessage Navigates the WebView to a URI with a POST request and HTTP headers.
OnApplyTemplate Invoked whenever application code or internal processes (such as a rebuilding layout pass) call ApplyTemplate. In simplest terms, this means the method is called just before a UI element displays in your app. Override this method to influence the default post-template logic of a class. (Se hereda de FrameworkElement)
OnCreateAutomationPeer When implemented in a derived class, returns class-specific AutomationPeer implementations for the Microsoft UI Automation infrastructure. (Se hereda de UIElement)
OnDisconnectVisualChildren Override this method to implement how layout and logic should behave when items are removed from a class-specific content or children property. (Se hereda de UIElement)
ReadLocalValue Returns the local value of a dependency property, if a local value is set. (Se hereda de DependencyObject)
Refresh Reloads the current content in the WebView.
ReleasePointerCapture Releases pointer captures for capture of one specific pointer by this UIElement. (Se hereda de UIElement)
ReleasePointerCaptures Releases all pointer captures held by this element. (Se hereda de UIElement)
RemoveHandler Removes the specified routed event handler from this UIElement. Typically the handler in question was added by AddHandler. (Se hereda de UIElement)
SetBinding Attaches a binding to a FrameworkElement, using the provided binding object. (Se hereda de FrameworkElement)
SetValue Sets the local value of a dependency property on a DependencyObject. (Se hereda de DependencyObject)
Stop Halts the current WebView navigation or download.
TransformToVisual Returns a transform object that can be used to transform coordinates from the UIElement to the specified object. (Se hereda de UIElement)
UpdateLayout Ensures that all positions of child objects of a UIElement are properly updated for layout. (Se hereda de UIElement)

 

Propiedades

WebViewClase tiene estas propiedades.

PropiedadTipo de accesoDescripción

ActualHeight

De sólo lecturaGets the rendered height of a FrameworkElement. (Se hereda de FrameworkElement)

ActualWidth

De sólo lecturaGets the rendered width of a FrameworkElement. (Se hereda de FrameworkElement)

AllowDrop

Lectura/escrituraGets or sets a value that determines whether this UIElement can be a drop target for purposes of drag-and-drop operations. (Se hereda de UIElement)

AllowedScriptNotifyUris

Lectura/escrituraGets or sets a safe list of URIs that are permitted to fire ScriptNotify events to this WebView.

AllowedScriptNotifyUrisProperty

De sólo lecturaIdentifies the AllowedScriptNotifyUris dependency property.

AnyScriptNotifyUri

De sólo lecturaGets a value that you can use to set the AllowedScriptNotifyUris property to indicate that any page can fire ScriptNotify events to this WebView.

BaseUri

De sólo lecturaGets a Uniform Resource Identifier (URI) that represents the base Uniform Resource Identifier (URI) for an XAML-constructed object at XAML load time. This property is useful for Uniform Resource Identifier (URI) resolution at run time. (Se hereda de FrameworkElement)

CacheMode

Lectura/escrituraGets or sets a value that indicates that rendered content should be cached as a composited bitmap when possible. (Se hereda de UIElement)

CanGoBack

De sólo lecturaGets a value that indicates whether there is at least one page in the backward navigation history.

CanGoBackProperty

De sólo lecturaIdentifies the CanGoBack dependency property.

CanGoForward

De sólo lecturaGets a value that indicates whether there is at least one page in the forward navigation history.

CanGoForwardProperty

De sólo lecturaIdentifies the CanGoForward dependency property.

Clip

Lectura/escrituraGets or sets the RectangleGeometry used to define the outline of the contents of a UIElement. (Se hereda de UIElement)

CompositeMode

Lectura/escrituraGets or sets a property that declares alternate composition and blending modes for the element in its parent layout and window. This is relevant for elements that are involved in a mixed XAML / Microsoft DirectX UI. (Se hereda de UIElement)

DataContext

Lectura/escrituraGets or sets the data context for a FrameworkElement when it participates in data binding. (Se hereda de FrameworkElement)

DataTransferPackage

De sólo lecturaGets a clipboard DataPackage as passed to the WebView.

DataTransferPackageProperty

De sólo lecturaIdentifies the DataTransferPackage dependency property.

DefaultBackgroundColor

Lectura/escrituraGets or sets the color to use as the WebView background when the HTML content does not specify a color.

DefaultBackgroundColorProperty

De sólo lecturaIdentifies the DefaultBackgroundColor dependency property.

DesiredSize

De sólo lecturaGets the size that this UIElement computed during the measure pass of the layout process. (Se hereda de UIElement)

Dispatcher

De sólo lecturaGets the CoreDispatcher that this object is associated with. (Se hereda de DependencyObject)

DocumentTitle

De sólo lecturaGets the title of the page currently displayed in the WebView.

DocumentTitleProperty

De sólo lecturaIdentifies the DocumentTitle dependency property.

FlowDirection

Lectura/escrituraGets or sets the direction in which text and other UI elements flow within any parent element that controls their layout. This property can be set to either LeftToRight or RightToLeft. Setting FlowDirection to RightToLeft on any element sets the alignment to the right, the reading order to right-to-left and the layout of the control to flow from right to left. (Se hereda de FrameworkElement)

Height

Lectura/escrituraGets or sets the suggested height of a FrameworkElement. (Se hereda de FrameworkElement)

HorizontalAlignment

Lectura/escrituraGets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Se hereda de FrameworkElement)

IsDoubleTapEnabled

Lectura/escrituraGets or sets a value that determines whether the DoubleTapped event can originate from that element. (Se hereda de UIElement)

IsHitTestVisible

Lectura/escrituraGets or sets whether the contained area of this UIElement can return true values for hit testing. (Se hereda de UIElement)

IsHoldingEnabled

Lectura/escrituraGets or sets a value that determines whether the Holding event can originate from that element. (Se hereda de UIElement)

IsRightTapEnabled

Lectura/escrituraGets or sets a value that determines whether the RightTapped event can originate from that element. (Se hereda de UIElement)

IsTapEnabled

Lectura/escrituraGets or sets a value that determines whether the Tapped event can originate from that element. (Se hereda de UIElement)

Language

Lectura/escrituraGets or sets localization/globalization language information that applies to a FrameworkElement, and also to all child elements of the current FrameworkElement in the object representation and in UI. (Se hereda de FrameworkElement)

ManipulationMode

Lectura/escrituraGets or sets the ManipulationModes value used for UIElement behavior and interaction with gestures. Setting this value enables handling the manipulation events from this element in app code. (Se hereda de UIElement)

Margin

Lectura/escrituraGets or sets the outer margin of a FrameworkElement. (Se hereda de FrameworkElement)

MaxHeight

Lectura/escrituraGets or sets the maximum height constraint of a FrameworkElement. (Se hereda de FrameworkElement)

MaxWidth

Lectura/escrituraGets or sets the maximum width constraint of a FrameworkElement. (Se hereda de FrameworkElement)

MinHeight

Lectura/escrituraGets or sets the minimum height constraint of a FrameworkElement. (Se hereda de FrameworkElement)

MinWidth

Lectura/escrituraGets or sets the minimum width constraint of a FrameworkElement. (Se hereda de FrameworkElement)

Name

Lectura/escrituraGets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Se hereda de FrameworkElement)

Opacity

Lectura/escrituraGets or sets the degree of the object's opacity. (Se hereda de UIElement)

Parent

De sólo lecturaGets the parent object of this FrameworkElement in the object tree. (Se hereda de FrameworkElement)

PointerCaptures

De sólo lecturaGets the set of all captured pointers, represented as Pointer values. (Se hereda de UIElement)

Projection

Lectura/escrituraGets or sets the perspective projection (3-D effect) to apply when rendering this element. (Se hereda de UIElement)

RenderSize

De sólo lecturaGets the final render size of a UIElement. (Se hereda de UIElement)

RenderTransform

Lectura/escrituraGets or sets transform information that affects the rendering position of a UIElement. (Se hereda de UIElement)

RenderTransformOrigin

Lectura/escrituraGets or sets the origin point of any possible render transform declared by RenderTransform, relative to the bounds of the UIElement. (Se hereda de UIElement)

RequestedTheme

Lectura/escrituraGets or sets the UI theme that is used by the UIElement (and its child elements) for resource determination. The UI theme you specify with RequestedTheme can override the app-level RequestedTheme. (Se hereda de FrameworkElement)

Resources

Lectura/escrituraGets the locally defined resource dictionary. In XAML, you can establish resource items as child object elements of a frameworkElement.Resources property element, through XAML implicit collection syntax. (Se hereda de FrameworkElement)

Source

Lectura/escrituraGets or sets the Uniform Resource Identifier (URI) source of the HTML content to display in the WebView control.

SourceProperty

De sólo lecturaIdentifies the Source dependency property.

Style

Lectura/escrituraGets or sets an instance Style that is applied for this object during layout and rendering. (Se hereda de FrameworkElement)

Tag

Lectura/escrituraGets or sets an arbitrary object value that can be used to store custom information about this object. (Se hereda de FrameworkElement)

Transitions

Lectura/escrituraGets or sets the collection of Transition style elements that apply to a UIElement. (Se hereda de UIElement)

Triggers

De sólo lecturaGets the collection of triggers for animations that are defined for a FrameworkElement. Not commonly used. (Se hereda de FrameworkElement)

UseLayoutRounding

Lectura/escrituraGets or sets a value that determines whether rendering for the object and its visual subtree should use rounding behavior that aligns rendering to whole pixels. (Se hereda de UIElement)

VerticalAlignment

Lectura/escrituraGets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Se hereda de FrameworkElement)

Visibility

Lectura/escrituraGets or sets the visibility of a UIElement. A UIElement that is not visible is not rendered and does not communicate its desired size to layout. (Se hereda de UIElement)

Width

Lectura/escrituraGets or sets the width of a FrameworkElement. (Se hereda de FrameworkElement)

 

Comentarios

Utilice el control WebView para hospedar contenido web en la aplicación. Observe que el comportamiento del control ha cambiado a partir de Windows 8.1. Para obtener información más detallada, vea a continuación.

WebView no es una subclase de Control y, en consecuencia, no tiene una plantilla de control. El área de presentación está restringida por las propiedades Width y Height.

Aunque la clase WebView no sea una subclase Control, puede recibir el foco de entrada de teclado y participar en la secuencia de pestaña. Proporciona un método Focus y los eventos GotFocus y LostFocus, pero no tiene propiedades relacionadas con la secuencia de tabulación. Su posición en la secuencia de tabulación es la misma que la que ocupa en el orden del documento XAML. La secuencia de tabulación incluye todos los elementos del contenido WebView que pueden recibir el foco de entrada.

Tal como se indica en la tabla de eventos, la clase WebView no es compatible con la mayoría de los eventos de entrada del usuario que se heredan de la clase UIElement como, por ejemplo, los eventos KeyDown, KeyUp y PointerPressed. Una solución alternativa común a este problema es utilizar WebView.InvokeScript (InvokeScriptAsync a partir de Windows 8.1) con eval para utilizar controladores de eventos de HTML, y utilizar window.external.notify desde el controlador de eventos HTML para notificar a la aplicación mediante WebView.ScriptNotify.

Además, WebView no admite actualmente algunas características de HTML5 incluidas AppCache, IndexedDB, acceso mediante programación al Portapapeles o geolocalización.

Windows 8

Estas notas solo se aplican a las aplicaciones compiladas para Windows 8, incluso cuando se ejecutan en Windows 8.1.

WebView tiene las características que otras regiones de la interfaz de usuario tales como los controles no pueden presentar encima de WebView. Este"problema de espacio aéreo" de se debe a la forma en que se administran internamente las regiones de la ventana, en concreto, cómo se procesan los eventos de entrada y cómo se dibuja en la pantalla. Si desea presentar contenido HTML, así como colocar otros elementos de la interfaz de usuario sobre dicho contenido, debe utilizar WebViewBrush como el área de presentación. WebView proporciona información del código fuente HTML y se hace referencia a dicho objeto WebView a través de la propiedad SourceName. WebViewBrush no tiene esta limitación de superposición.

Si desea mostrar un objeto WebView interactivo que raramente tiene contenido superpuesto (como una lista desplegable o una barra de aplicaciones), puede ocultar temporalmente el control WebView cuando sea necesario, reemplazándolo con un elemento que utilice un relleno WebViewBrush. A continuación, cuando el contenido superpuesto ya no aparece, puede mostrar el objeto WebView original de nuevo.

Nota  El “problema de espacio aéreo” se ha corregido a partir de Windows 8.1.

WebView siempre utiliza Internet Explorer 10 en modo de documento.

WebView no admite el esquema ms-appdata, aunque sí admite el esquema ms-appx-web, que puede utilizar para cargar archivos de contenido del paquete de la aplicación.



<WebView Source="ms-appx-web:///HTMLPage1.html"/>


Windows 8.1

Windows 8.1 presenta cambios en el control WebView que corrigen varios problemas y agregan nueva funcionalidad, incluido:

WebView siempre utiliza Internet Explorer 11 en modo de documento.

Windows 8.1 desusa las API WebView siguientes:

Estos cambios no afectan a las aplicaciones compiladas para Windows 8, incluso cuando se ejecutan en Windows 8.1.

Ejemplos

En el ejemplo de código siguiente se muestra cómo navegar un objeto WebView a un URI contenido en TextBox denominado Address. La lista de código completa de este ejemplo y los siguientes está disponible en el ejemplo de control WebView.


try
{
    Uri targetUri = new Uri(Address.Text);
    WebView1.Navigate(targetUri);
}
catch (FormatException ex)
{
    // Bad address.
}


En el ejemplo de código siguiente se muestra cómo cargar el valor local HTML en un control de WebView.


WebView2.NavigateToString(
    "<html><body><h2>This is an HTML fragment</h2></body></html>");

El ejemplo de código siguiente muestra cómo usar un control WebView para llamar a una función JavaScript incluida en HTML que ha cargado.

Nota  A partir de Windows 8.1, debe utilizar InvokeScriptAsync en lugar de InvokeScript.


string htmlFragment = 
    "<html><head><script type='text/javascript'>function SayGoodbye() { " +
    "document.getElementById('myDiv').innerText = 'GoodBye'; } " +
    "</script></head><body><div id='myDiv'>Hello</div></body></html>";

WebView3.NavigateToString(htmlFragment);

WebView3.InvokeScript("SayGoodbye", null);


Requisitos

Cliente mínimo admitido

Windows 8 [Solo aplicaciones de la Tienda Windows]

Servidor mínimo admitido

Windows Server 2012 [Solo aplicaciones de la Tienda Windows]

Espacio de nombres

Windows.UI.Xaml.Controls
Windows::UI::Xaml::Controls [C++]

Metadatos

Windows.winmd

Vea también

FrameworkElement
Ejemplo de control WebView de XAML

 

 

Mostrar:
© 2015 Microsoft