我无法从另一个DataTemplate
中绑定到DataTemplate
,这是因为数据源在运行时不存在吗?
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Resources>
<DataTemplate x:Key="Employees">
<StackPanel>
<ListView ItemsSource="{Binding Path=Employees}">
<ListView.View>
<GridView>
<GridViewColumn Header="FirstName">
<GridViewColumn.CellTemplate>
<DataTemplate>
<DockPanel>
<TextBlock Text="{Binding FirstName}"/>
</DockPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="LastName">
<GridViewColumn.CellTemplate>
<DataTemplate>
<DockPanel>
<TextBlock Text="{Binding LastName}"/>
</DockPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="Company">
<StackPanel>
<TextBlock>Company data</TextBlock>
<ListView
<!-- Bind current data source -->
ItemsSource="{Binding}"
<!-- Static resource (nested template) -->
ItemTemplate="{StaticResource Employees}" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<StackPanel>
<TextBlock>Companies:</TextBlock>
<ListView ItemsSource="{Binding Companies}" ItemTemplate="{StaticResource Company}" />
</StackPanel>
</Page>
我正在尝试让员工DataTemplate
可重复使用,因为在其他数据DataTemplate
中引用会很有用。公司DataTemplate
中的绑定是否有问题:<ListView ItemsSource="{Binding}" ItemTeplate="{StaticResource Employees}" />
为什么员工不会受到约束?
答案 0 :(得分:4)
为我工作。 DataContext是否已设置?在我尝试这件事时,这让我感到沮丧。
的Xaml
<StackPanel>
<StackPanel.Resources>
<DataTemplate x:Key="_Chest">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding WeightInKgs, StringFormat=Contains \{0\} kgs of : }"/>
<TextBlock Text="{Binding Contents}"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="_Gallery">
<ListBox ItemsSource="{Binding}" ItemTemplate="{StaticResource _Chest}" Background="Aqua"/>
</DataTemplate>
</StackPanel.Resources>
<ContentControl Content="{Binding Treasures}" ContentTemplate="{StaticResource _Gallery}" Background="Coral"/>
</StackPanel>
背后的代码
public MainWindow()
{
InitializeComponent();
Treasures = new List<Chest>{new Chest{Contents = "Gems", WeightInKgs=10},
new Chest{Contents = "Gold", WeightInKgs= 25}};
this.DataContext = this;
}
public List<Chest> Treasures { get; set; }