I have a working custom markup extension that retrieves information from a DataContext specific way (not relevant for this question).
Everything is fine until I use this markup extension in elements that are not part of the visual or logical tree. In my specific example, in an InputBindings element. In this scenario, instead of getting FrameworkElement as DependencyObject I get a Freezable ( KeyBinding ).
How can I access a DataContext through code?
My XAML code:
<UserControl.InputBindings> <KeyBinding Key="CapsLock" Command="{wtc:CommandBinding {x:Static b:Commands.OpenTimeLine}}" /> </UserControl.InputBindings>
Code in my custom markup extension where I usually retrieve my DataContext :
protected override object ProvideValue( DependencyObject dependencyObject, DependencyProperty dependencyProperty ) { if ( dependencyObject is Freezable ) { // TODO: How to handle freezable? } _frameworkElement = dependencyObject as FrameworkElement; if ( _frameworkElement == null ) { throw new InvalidImplementationException( "The DataContextBinding may only be used on framework elements." ); } if ( !_dataContextChangedHooked ) { _frameworkElement.DataContextChanged += DataContextChanged; _dataContextChangedHooked = true; } return ProvideValue( _frameworkElement.DataContext ); }
All source code is also online. I have a fairly extensive class hierarchy for markup extensions.
AbstractMarkupExtension ⇐ AbstractDependencyPropertyBindingExtension ⇐ AbstractDataContextBindingExtension ⇐ CommandBindingExtension
source share