【问题标题】:DataBinding inside a ContentTemplate inside a Style in Silverlight在 Silverlight 中的样式内的 ContentTemplate 内的 DataBinding
【发布时间】:2013-02-18 19:38:54
【问题描述】:

我在 XAML 中定义了以下样式:

 <Style TargetType="telerik:RadDiagramShape" x:Key="styleShapeBase">
    <Setter Property="Width" Value="120" />
    <Setter Property="Height" Value="60" />
    <Setter Property="IsResizingEnabled" Value="False" />
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock x:Name="lblName" Text="{Binding Name}" />
            </DataTemplate>
        </Setter.Value>
     </Setter>
</Style>

然后在代码隐藏中我分配数据上下文。我想绘制一个形状,其中包含来自对象的一些文本(如果这最终起作用,我将在那里放置更多信息)。我是这样做的:

var shape = new RadDiagramShape();
shape.Style = (Style)Resources["styleShapeBase"];
shape.DataContext = item.DataContext;

item 是一个简单的 POCO,它具有类型为 stringName 属性(这部分有效,我已经跟踪它,即正确分配了 DataContext)。

数据绑定永远不会发生。是否是设计使然(即内容模板内没有数据绑定),如果不是有什么问题?谢谢,

【问题讨论】:

标签: silverlight xaml data-binding styles


【解决方案1】:

您可以在 DataTemplates 中使用绑定。在这种情况下,绑定将在您设置为 RadDiagramShape 内容的任何内容上查找 Name 属性。

你应该确保你的类有这个属性并且它是一个字符串。

如果这仍然不起作用,您能否详细说明如何设置 RadDiagramShape 的每个实例的样式和内容,以及您尝试绑定到的对象?


在 RadDiagramShape 类的控制模板中的某处,会有一个 ContentPresenter,它的 ContentTemplate 绑定到您定义的那个。问题是 ContentTemplate 仅在同时设置了 Content 属性时才使用。否则,不会将任何内容加载到该 ContentPresenter 中。

要完成这项工作,您必须在此元素的实例上设置 Content 属性。

This is a good place to start understanding what the DataContext property is

【讨论】:

  • 好的,所以我什至不必设置 DataContext 属性?设置Content时是隐含的?
  • 除非您想通过数据绑定定义内容,否则您不必设置DataContext。必须始终设置内容。
  • "要完成这项工作,您必须在此元素的实例上设置 Content 属性。" - 非常感谢您指出这一点,这完全解决了问题。我应该已经知道这一点了,但是仅仅看我的代码我还是看不到这个问题。
猜你喜欢
  • 1970-01-01
  • 2011-03-15
  • 2011-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 2020-06-16
相关资源
最近更新 更多