FrameworkElement.DataContextChanged 事件

定义

FrameworkElement.DataContext 属性的值更改时发生。

// Register
event_token DataContextChanged(TypedEventHandler<FrameworkElement, DataContextChangedEventArgs const&> const& handler) const;

// Revoke with event_token
void DataContextChanged(event_token const* cookie) const;

// Revoke with event_revoker
FrameworkElement::DataContextChanged_revoker DataContextChanged(auto_revoke_t, TypedEventHandler<FrameworkElement, DataContextChangedEventArgs const&> const& handler) const;
public event TypedEventHandler<FrameworkElement,DataContextChangedEventArgs> DataContextChanged;
function onDataContextChanged(eventArgs) { /* Your code */ }
frameworkElement.addEventListener("datacontextchanged", onDataContextChanged);
frameworkElement.removeEventListener("datacontextchanged", onDataContextChanged);
- or -
frameworkElement.ondatacontextchanged = onDataContextChanged;
Public Custom Event DataContextChanged As TypedEventHandler(Of FrameworkElement, DataContextChangedEventArgs) 
<frameworkElement DataContextChanged="eventhandler"/>

事件类型

注解

FrameworkElement.DataContext 属性具有内置行为,通过该行为,其值将继承到设置了 DataContext 值的 FrameworkElement 的所有 FrameworkElement 子元素。 此行为使一组相关元素能够使用相同的上下文绑定到不同的源属性,这对于项模板、数据模板和其他数据绑定方案特别有用。 由于 DataContext 继承,因此,一旦元素检测到继承的 DataContext 值已更改,每个 FrameworkElement 都有可能触发另一个DataContextChanged事件,该事件源自继承元素而不是父元素。 如果不希望此行为,则应处理 DataContextChanged 父源上的 事件,其中事件将首先触发。 作为处理程序逻辑的一部分,将 DataContextChangedEventArgs 事件数据中 Handled 属性的值设置为 true。 该操作将阻止事件路由到子元素。

注意

DataContextChanged 具有路由行为,但不是真正的路由事件, (它没有 RoutedEvent 标识符) 。 此外,它从父级路由到子级,而真正的路由事件从子路由到父级。 如果熟悉 WPF) Windows Presentation Foundation (,DataContextChanged则 WPF) 事件路由定义Windows Presentation Foundation (可能将它视为隧道路由事件。

DataContextChanged 对于控制逻辑或其他基于代码的逻辑需要绑定的数据上下文已更改的通知(这通常意味着数据绑定值将更改)的方案非常有用。 这可用作运行进行上下文驱动更改的代码的触发器,然后现有绑定可以使用新上下文来重新计算值。 如果不希望数据模板中预先存在的已声明绑定,但需要更改通知,则此功能也很有用。 在此方案中,你可以处理 DataContextChanged 以检测对数据上下文的更改,并直接更改代码中的其他属性以响应,就像 XAML 声明的绑定通过数据绑定引擎动态执行一样。 例如,你可能有一个主要用于在数据模板内部使用的自定义控件,并且你希望该控件能够在应用 UI XAML 或数据模板中执行任何显式 Binding 声明的情况下执行绑定操作。

适用于

另请参阅