控件模板的DataContext是如何设置的?

4

我正在为Tile控件(在Telerik TileList中)设置ControlTemplate。它看起来像这样:

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

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

            <ContentPresenter Content="{Binding}" />

    </Border>
</ControlTemplate>

其他地方:

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

我已经为Tile的ContentPresenter中呈现的项目定义了DataTemplates。 我遇到的问题是,当将ComponentViewModel添加到ItemsSource(ComponentViewModel ObservableCollection)的目标中时,会出现一个新的Tile,但它的DataContext是RadTileList的ViewModel而不是单个组件的ViewModel。

在ControlTemplate中设置DataContext时是否漏掉了什么?


对我来说,这似乎是一个Telerik的bug。遵循WPF的ItemsControl哲学,ItemContainers(在这种情况下是Tiles)应该将它们的数据上下文设置为ItemsSource集合中相应的项。就像任何其他基于ItemsControl的UI元素一样。 - Federico Berasategui
我已经向Telerik提交了一张工单。希望这不是唯一的解决方案... - Brian Triplett
2个回答

2
要在DataTemplate内部绑定到父视图或控件的DataContext上附加的Presenter或ViewModel上的属性,您必须使用RelativeSource属性,并使用值“FindAncestor”和您正在查找的具有DataContext的控件类型。
我看到最常见的错误是人们忘记为AcestorType属性使用{x:Type yourControlType}标记扩展,而是使用“AncestorType = yourControlType”。
以下是一个示例:
Width="{Binding DataContext.SomeProperty, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"

“SomeProperty” 是 Presenter 或 ViewModel 上遵循 INotifyPropertyChanged 模式的属性。

Width 是 ControlTemplate 内控件的属性。


0

看起来这样做就可以了。我需要对ContentTemplate和Content属性进行TemplateBinding。

<ControlTemplate TargetType="{x:Type telerik:Tile}">
    <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}"/>

</ControlTemplate>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接