Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the DataContext of a ControlTemplate set?

I am setting the ControlTemplate in a Tile control (in the Telerik TileList). It looks something like this:

<ControlTemplate TargetType="{x:Type telerik:Tile}">
    <Border>

        <!-- Some Content that binds to DP on the view models -->

            <ContentPresenter Content="{Binding}" />

    </Border>
</ControlTemplate>

Elsewhere:

<telerik:RadTileList ItemsSource="{Binding ComponentViewModels}">

And I have DataTemplates defined for the items that would be presented within the Tile's ContentPresenter. The trouble I have is that, when a ComponentViewModel is added to the target of the ItemsSource (ComponentViewModel ObservableCollection) a new Tile appears but it's DataContext is the RadTileList's ViewModel and not the individual component's ViewModel.

Am I missing something regarding the setting of the DataContext in a ControlTemplate?

like image 920
Brian Triplett Avatar asked Dec 18 '25 12:12

Brian Triplett


1 Answers

To bind to a property on the Presenter or ViewModel attached to the DataContext on the parent view or control from inside a DataTemplate you have to use the RelativeSource property with the value “FindAncestor” and the type of the control with the DataContext you are looking for.

The most common mistake I’ve seen using this, is people forgetting to use the {x:Type yourControlType} markup extension for the AcestorType property and using “AncestorType=yourControlType” instead.

Here is an example:

Width="{Binding DataContext.SomeProperty, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"

where “SomeProperty” is a property on the Presenter or ViewModel that follows the INotifyPropertyChanged pattern.

Width is the property of the control inside the the ControlTemplate

like image 100
Raiden Core Avatar answered Dec 20 '25 02:12

Raiden Core



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!