【发布时间】:2010-05-27 20:50:15
【问题描述】:
我正计划编写类似于组织结构图的分层组织控制。有几个组织结构图实现,但不太符合我的想法。
将DataTemplate 中的字段绑定到自定义对象似乎不起作用。
我从一个通用的自定义控件开始,即
public class NodeBodyBlock : ContentControl
{
public NodeBodyBlock()
{
this.DefaultStyleKey = typeof(NodeBodyBlock);
}
}
在generic.xaml有一个简单的风格:
<Style TargetType="org:NodeBodyBlock">
<Setter Property="Width" Value="200" />
<Setter Property="Height" Value="100" />
<Setter Property="Background" Value="Lavender" />
<Setter Property="FontSize" Value="11" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="org:NodeBodyBlock">
<Border Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"
Background="{TemplateBinding Background}" CornerRadius="4" BorderBrush="Black" BorderThickness="1" >
<Grid>
<VisualStateManager/> ... clipped for brevity
</VisualStateManager.VisualStateGroups>
<ContentPresenter Content="{TemplateBinding Content}"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我现在的计划是能够使用这个通用定义作为各种基本定义,并使用它的定制版本来显示不同类型的内容。
一个简单的例子是在具有以下样式的用户控件上使用它:
<Style TargetType="org:NodeBodyBlock" x:Key="TOCNode2">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=NodeTitle}"/>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
和一个定义为
的实例<org:NodeBodyBlock Style="{StaticResource TOCNode2}" x:Name="stTest"
DataContext="{StaticResource DummyData}" />
DummyData 定义为
<toc:Node NodeNumber="mynum" NodeStatus="A"
NodeTitle="INLine Node Title!"
x:Key="DummyData"/>
后面有一个简单的 C# 类,其中每个字段都是公共属性。
运行应用程序时,虚拟数据值根本不会显示在 GUI 中。一个简单的测试,例如
<TextBlock Text="{Binding NodeTitle}" DataContext="{StaticResource DummyData}"/>
工作得很好。
关于我错过情节的任何想法?
更新:绑定到 generic.xaml 中定义中的 datacontext 可以正常工作,但 ContentPresenter 中的任何绑定都会丢失。
【问题讨论】:
-
您是否在任何地方设置 NodeBodyBlock 的内容?您似乎正在设置 DataContext,但您的 ContentPresenter 绑定到 Content 而不是 DataContext。
标签: silverlight binding custom-controls