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 (,则 Windows Presentation Foundation (WPF) 事件路由定义可将 DataContextChanged 视为隧道路由事件。

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

适用于

另请参阅